I am creating a java application which calls some service via https. But whenever I call any api I need to set my proxy via System.setProperty("https.proxyHost","some proxy host");.That too is a system dependent because proxy host can change on changing the system.Why doesn't is pick proxy automatically like browsers do. Is there any way to configure is once or make it auto detect the proxy settings ?
-
It seems a duplicate of this : http://stackoverflow.com/questions/5910001/how-to-get-proxy-settings-from-system-settings-in-java – davidxxx Jun 07 '15 at 11:34
-
@davidh Note that the supposedly original mentioned here is actually incomplete or does not correctly address the issue. I will work this out later in that article too. For more information, see [one of my earlier posts](http://stackoverflow.com/a/31391184/744133) answering some of that in a different context. – YoYo Jul 15 '15 at 18:14
2 Answers
You can set it to use the systems proxy settings, just like your browser can do, by setting the System property java.net.useSystemProxies
to true
. By doing in your code:
System.setProperty("java.net.useSystemProxies","true");
On the command line
java -Djava.net.useSystemProxies=true ...
Or in the ${java.home}/lib/net.properties
file as a default for the JRE. See more on one of my previous answers.
Note that this will only work if nowhere else you try to manually set the proxy in your code (System::setProperty) or in the command line (-Dhttp.proxyHost=some.proxy.host
). Manually setting the proxy would simply undo this.
If you are running through a proxy, then yes you will have to specify it yourself unless it is already set as an environment variable on the system.
You can specify the proxy when running the application. Something like:
java -Dhttp.proxyHost=some.proxy.host
Also, do not forget to specify the non-proxy host
The correct approach is to let the user type in the proxy details if any is required
-
This does not make it to use the System default settings (of your host machine), but actually overrides it. This is not what the OP wants, although he/she/it has a little trouble framing the question. – YoYo Jul 15 '15 at 18:16