如何使用java测试代理互联网连接?
我有一些代码来测试代理服务器和端口是否正常工作,其中一些代码如下所示:
System.getProperties().put("proxySet", "true");
System.getProperties().put("https.proxyHost", "localhost");
System.getProperties().put("https.proxyPort", "1234");
System.getProperties().put("http.proxyHost", "localhost");
System.getProperties().put("http.proxyPort", "1234");
HttpURLConnection conn = (HttpURLConnection) new URL("https://www.google.com").openConnection();
conn.getContent();
conn.disconnect();
似乎 openConnection() 方法会执行如下操作:
- 尝试连接给定的 URL使用代理。
- 如果无法使用代理,则会直接连接 URL,无需代理。
这就是问题所在,我的意思是测试代理是否正常工作,但是如果代理无法连接,此代码将不会停止。
我还尝试使用 InetAddress 类的 isReachable() 方法,但得到了相同的结果。
那么如果代理不起作用,我该如何停止此连接,以测试代理是否可用可达?
i have some code to test if the proxy server and port is working ,some of the code like this:
System.getProperties().put("proxySet", "true");
System.getProperties().put("https.proxyHost", "localhost");
System.getProperties().put("https.proxyPort", "1234");
System.getProperties().put("http.proxyHost", "localhost");
System.getProperties().put("http.proxyPort", "1234");
HttpURLConnection conn = (HttpURLConnection) new URL("https://www.google.com").openConnection();
conn.getContent();
conn.disconnect();
it seems that openConnection() method will do thing like this:
- try to connect given URL using proxy.
- if it fails to use proxy,it will connect URL directly without proxy.
that's the problem,i meant to test if the proxy is working,but this code won't stop if the proxy can not connect.
i also tried to use isReachable() method of InetAddress class,but i get the same result.
so how could i stop this connection if the proxy doesn't work ,in order to test if the proxy is reachable ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那个什么也不做。这是一个都市神话。它是已失效的 1997 HotJava bean 的一部分,并从那里泄漏到各种书籍中。它从未成为任何 JDK 的一部分。在某些需要它的情况下尝试将其设置为
false
并亲自查看。That one doesn't do anything. It is an urban myth. It was part of the defunct 1997 HotJava bean and leaked from there into various books. It has never been part of any JDK. Try setting it to
false
in some situation where you need it on and see for yourself.抱歉各位,我找到了方法。
我使用 java.net.Proxy 类通过代理打开连接。
它易于使用且运行良好。请参阅 Java 网络和代理
Sorry guys, I found out the way to do it.
I used
java.net.Proxy
class to open a connection via proxy.It's easy to use and works fine. See Java Networking and Proxies