Setting proxy for java application

12.5k views Asked by At

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 ?

2

There are 2 answers

1
AbuHayA On

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

0
YoYo On

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.