在 java、URL 与 System.setProperty 中设置代理?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1373979/
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
Setting proxy in java, URL vs System.setProperty?
提问by
I made an java app that gets a response time from the internet. I'm working from behind a proxy, now I have this problem that I can't figure out, here's a snipped of my code
我制作了一个从互联网获取响应时间的 Java 应用程序。我在代理后面工作,现在我遇到了我无法弄清楚的问题,这是我的代码片段
URL website = new URL("http", proxy, Integer.parseInt(proxyPort), websiteUrl)
BufferedReader in = new BufferedReader(new InputStreamReader(website.openStream()));
long start = System.currentTimeMillis();
while ((in.readLine()) != null){}
long elapsedTimeMillis = System.currentTimeMillis()-start;
Vs
对比
URL website = new URL(websiteUrl);
System.setProperty("http.proxyHost", proxy);
System.setProperty("http.proxyPort", proxyPort);
BufferedReader in = new BufferedReader(new InputStreamReader(website.openStream()));
long start = System.currentTimeMillis();
while ((in.readLine()) != null){}
long elapsedTimeMillis = System.currentTimeMillis()-start;
When I use
当我使用
URL website = new URL(websiteUrl);
System.setProperty("http.proxyHost", proxy);
System.setProperty("http.proxyPort", proxyPort);
I get a response time of 0.064 on average
我的平均响应时间为 0.064
and when I use
当我使用
URL website = new URL("http", proxy, Integer.parseInt(proxyPort), websiteUrl)
I get a much higher response time of 0.219. How can I tell which one is giving me an accurate timing?
我得到了 0.219 的更高响应时间。我怎么知道哪个给了我一个准确的时间?
回答by fg.
Check the Javadoc form the contructor you're using to instantiate your URL in the first case, it's not doing what you want:
在第一种情况下检查用于实例化 URL 的构造函数的 Javadoc,它没有做你想要的:
URL(String protocol, String host, int port, String file) Creates a URL object from the specified protocol, host, port number, and file.
In the second case you call your website thru your proxy, in the first you're calling your proxy as a web server, with something like
在第二种情况下,您通过代理调用您的网站,在第一种情况下,您将代理称为网络服务器,类似
http://proxyhost:3128/http://mysite.com/index.html
... the response is not what you expect, and you stay in your LAN, thus the times very different.
...响应不是您所期望的,并且您留在您的局域网中,因此时代非常不同。
回答by laz
That first version actually using a proxy. It is making an HTTP request to the proxy server. I'd recommend running your tests again but look at the HTTP response code and inspect the actual output from the URL's InputStream to see what response you are getting.
第一个版本实际上使用了代理。它正在向代理服务器发出 HTTP 请求。我建议再次运行您的测试,但查看 HTTP 响应代码并检查来自 URL 的 InputStream 的实际输出以查看您得到的响应。

