在测试中,我这样做:
System.setProperty("http.proxyHost", "localhost");
System.setProperty("http.proxyPort", "1080");
然后打开连接:
connection = (HttpURLConnection)url.openConnection();
if (connection.usingProxy()) {
throw new Nope();
}
正在使用代理,否则连接会失败。但是 usingProxy()
返回 false。
我错过了什么?
最佳答案
this page 中有大量详细信息。讨论在应用程序中设置代理的不同方式,以及连接如何使用代理。
您还可以通过调试代码本身获得重要的理解,从而得出与页面中的描述一致的结论。
基本上,当满足以下条件时,usingProxy()
返回 true:
连接已实际创建。在您的代码中,
url.openConnection()
并不实际建立与 URL 的连接。您需要调用connection.connect()
(或隐式执行连接的操作)。openConnection()
的 Javadocs 中提到了这一点:It should be noted that a URLConnection instance does not establish the actual network connection on creation. This will happen only when calling URLConnection.connect().
代理集(使用系统属性或通过 java.net.Proxy 类)指向可访问的地址。因此,请确保代理
localhost:1080
是有效的代理。
关于第二点的更多细节。 HttpUrlConnection
依赖于 ProxySelector
类(在上面的页面中提到),该类查找注册的代理地址。默认的 ProxySelector 会忠实地获取您在系统属性中设置的代理,而 HttpUrlConnection 会尝试访问该代理。如果不可用,它将向 ProxySelector 请求另一个代理(如果存在另一个代理)。
我发现文档中包含的对话框是一个很好的解释(斜体部分突出显示了连接到代理的尝试):
Handler: Hey dude, I'm trying to reach java.example.org, should I use a proxy?
ProxySelector: Which protocol do you intend to use?
Handler: http, of course!
ProxySelector: On the default port?
Handler: Let me check.... Yes, default port.
ProxySelector: I see. Then you shall use webcache.example.com on port 8080 as a proxy.
Handler: Thanks. <pause> Dude, webcache.example.com:8080 doesn't seem to be responding! Any other option?
ProxySelector: Dang! OK, try webcache2.example.com, on port 8080 as well.
Handler: Sure. Seems to be working. Thanks.
ProxySelector: No sweat. Bye.
(作者确实提到这是一个经过修饰的对话框。)
关于java - HttpUrlConnection.usingProxy() 什么时候返回 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34048170/