Search code examples
javaurlconnectionhttp-proxy

URLConnection doesn't use proxy settings


I have a problem with HttpsURLConnection - proxy is not used.
Here is the code:

//proxy
String type = "https";
System.getProperties().put(type + ".proxyHost", host);
System.getProperties().put(type + ".proxyPort", port);
System.getProperties().put(type + ".proxyUser", username);
System.getProperties().put(type + ".proxyPassword", password);

/*some SSL stuff*/

//connection
URL url = new URL(url0);
URLConnection urlConnection = url.openConnection();
urlConnection.setUseCaches(false);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(false);           
urlConnection.setRequestProperty("Connection", "Keep-Alive");   

HttpsURLConnection httpConn = (HttpsURLConnection)urlConnection;
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestProperty("Proxy-Authorization", "Basic " + Base64Converter.encode(username + ":" + password));
httpConn.connect();

All proxy settings are ignored by the connection and httpConn.usingProxy() is false.
I also tried to pass Proxy instance to url.openConnection() and setting proxy login/password to default Authenticator. The connection used proxy in that case, but I got 407, so it seems that Authenticator doesn't work correctly for me.


Solution

  • System.getProperties().put(type + ".proxyUser", username);
    System.getProperties().put(type + ".proxyPassword", password);
    

    According to the official documentation, the JRE does not recognized either of these. I believe the Apache HTTP Client may do so, but don't quote me.

    You need to install a java.net.Authenticator.