java 如何使用java测试代理互联网连接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3957599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:08:18  来源:igfitidea点击:

how to test proxy internet connection using java?

javanetworkingproxy

提问by Barry Wei

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:

似乎 openConnection() 方法会做这样的事情:

  1. try to connect given URL using proxy.
  2. if it fails to use proxy,it will connect URL directly without proxy.
  1. 尝试使用代理连接给定的 URL。
  2. 如果使用代理失败,它会直接连接 URL ,不使用代理

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.

我也尝试使用 InetAddress 类的 isReachable() 方法,但我得到了相同的结果。

so how could i stop this connection if the proxy doesn't work ,in order to test if the proxy is reachable ?

那么如果代理不起作用,我怎么能停止这个连接,以测试代理是否可达?

回答by user207421

System.getProperties().put("proxySet", "true");

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 falsein some situation where you need it on and see for yourself.

那一个什么都不做。这是一个都市神话。它是 1997 年不复存在的 HotJava bean 的一部分,并从那里泄露到各种书籍中。它从未成为任何 JDK 的一部分。尝试将其设置为false您需要的情况并亲自查看。

回答by Barry Wei

Sorry guys, I found out the way to do it. I used java.net.Proxyclass to open a connection via proxy. It's easy to use and works fine. See Java Networking and Proxies

对不起,伙计们,我找到了方法。我使用java.net.Proxyclass 通过代理打开连接。它易于使用且运行良好。请参阅Java 网络和代理