Skip to content
Advertisement

How do I make HttpURLConnection use a proxy?

If I do this…

conn = new URL(urlString).openConnection();
System.out.println("Proxy? " + conn.usingProxy());

it prints

Proxy? false

The problem is, I am behind a proxy. Where does the JVM get its proxy information from on Windows? How do I set this up? All my other apps seem perfectly happy with my proxy.

Advertisement

Answer

Since java 1.5 you can also pass a java.net.Proxy instance to the openConnection(proxy) method:

//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);

If your proxy requires authentication it will give you response 407.

In this case you’ll need the following code:

    Authenticator authenticator = new Authenticator() {

        public PasswordAuthentication getPasswordAuthentication() {
            return (new PasswordAuthentication("user",
                    "password".toCharArray()));
        }
    };
    Authenticator.setDefault(authenticator);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement