85

我正在尝试使用带有 URLConnection 的 Java 解析网页。我尝试像这样设置用户代理:

java.net.URLConnection c = url.openConnection();
c.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");

但生成的用户代理是我指定的,在末尾附加了“Java/1.5.0_19”。有没有办法在没有这个添加的情况下真正设置用户代理?

4

4 回答 4

95

只是为了澄清: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());
    }

}
于 2012-03-22T18:55:20.250 回答
75

顺便说一句,将http.agent系统属性设置为""可能会奏效(我面前没有代码)。

你可能会逃脱:

 System.setProperty("http.agent", "");

但这可能需要您和 URL 协议处理程序的初始化之间的竞争,如果它在启动时缓存值(实际上,我认为它不会)。

该属性也可以通过 JNLP 文件(适用于 6u10 的小程序)和命令行设置:

-Dhttp.agent=

或者对于包装器命令:

-J-Dhttp.agent=
于 2010-03-27T15:52:54.360 回答
5

它对我的工作是 在 addRequestProperty 中设置 User-Agent。

URL url = new URL(<URL>);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0");
于 2017-11-15T05:49:38.560 回答
2

HTTP 服务器倾向于拒绝旧的浏览器和系统。

The page Tech Blog (wh): Most Common User Agents reflects the user-agent property of your current browser in section "Your user agent is:", which can be applied to set the request property "User-Agent" of a java.net.URLConnection or the system property "http.agent".

于 2018-07-28T16:28:32.130 回答