只是为了澄清:现在工作得很好,不会在最后附加!至少在Java 1.6.30及更高版本中。setRequestProperty("User-Agent", "Mozilla ...")
java/xx
我用netcat(端口监听器)在我的机器上收听:
$ nc -l -p 8080
它只是在端口上侦听,所以你看到任何被请求的东西,比如原始的http-headers。
并得到了以下没有setRequestProperty的http-headers:
GET /foobar HTTP/1.1
User-Agent: Java/1.6.0_30
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
和 with setRequestProperty:
GET /foobar HTTP/1.1
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
如您所见,用户代理已正确设置。
完整示例:
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class TestUrlOpener {
public static void main(String[] args) throws IOException {
URL url = new URL("http://localhost:8080/foobar");
URLConnection hc = url.openConnection();
hc.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
System.out.println(hc.getContentType());
}
}