只是为了澄清:setRequestProperty("User-Agent", "Mozilla ...")
现在工作得很好,最后不会追加java/xx
!至少在 Java 1.6.30 和更新版本中。
我用 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
并使用 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());
}
}