问题描述
我正在尝试使用带有URLConnection的Java解析网页。我尝试像这样设置用户代理:
I'm trying to parse a webpage using Java with URLConnection. I try to set up the user-agent like this:
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结束。有没有办法真正设置用户代理而不添加这个?
But the resulting user agent is the one I specify, with "Java/1.5.0_19" appended to the end. Is there a way to truly set the user agent without this addition?
推荐答案
关闭,设置 http.agent
系统属性为可能会起作用(我没有代码在我面前)。
Off hand, setting the http.agent
system property to ""
might do the trick (I don't have the code in front of me).
你可能会逃脱:
System.setProperty("http.agent", "");
但是如果它缓存了值,那么可能需要在您和URL协议处理程序的初始化之间进行竞争在启动时(实际上,我不认为它)。
but that might require a race between you and initialisation of the URL protocol handler, if it caches the value at startup (actually, I don't think it does).
该属性也可以通过JNLP文件(可用于6u10的小程序)和命令行设置:
The property can also be set through JNLP files (available to applets from 6u10) and on the command line:
-Dhttp.agent=
或者对于包装器命令:
-J-Dhttp.agent=
这篇关于设置java URLConnection的用户代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!