Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting proxy in java, URL vs System.setProperty?

Tags:

java

proxy

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

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

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?


1 Answers

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(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.

like image 174
fg. Avatar answered Aug 30 '26 13:08

fg.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!