Search code examples
javaproxypac

Setting proxy as System properties not working


I'm trying to set a proxy to use in my application. When I try to set it as a system property:

Proxy proxy = ... // code to retrieve proxy from .pac file
InetSocketAddress addr = (InetSocketAddress) proxy.address();
System.setProperty("java.net.useSystemProxies", "true");
System.setProperty("http.proxyHost", addr.getHostName());
System.setProperty("http.proxyPort", Integer.toString(addr.getPort()));

it throws java.net.ConnectException: Connection timed out: connect when I try to connect to a URL:

URL url = new URL(urlToConnect);
HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection(); // Exception thrown in this line

But, if I set the proxy as a parameter to openConnection():

HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection(proxy); 

my code works and I am able to connect to URL, but this solution is impracticable since I have many openConnection() in my code.

How can I make it work when using it as system properties?


Solution

  • The URL I was trying to access was https and I was setting http.proxyHost and http.proxyPort. Changing it to https.proxyHost and https.proxyHost, it worked