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 : stackoverflow.com/questions/5910001/…davidxxx– davidxxx2015-06-07 11:34:28 +00:00Commented Jun 7, 2015 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 answering some of that in a different context.YoYo– YoYo2015-07-15 18:14:07 +00:00Commented Jul 15, 2015 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.
Comments
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