Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make HttpURLConnection use a proxy?

People also ask

How do I set proxy for Rest assured?

Instruct REST Assured to connect to a proxy on the specified port on localhost. Instruct REST Assured to connect to a proxy using a ProxySpecification . Instruct REST Assured to connect to a proxy on the specified host on port 8888 . Instruct REST Assured to connect to a proxy on the specified host and port.


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);

This is fairly easy to answer from the internet. Set system properties http.proxyHost and http.proxyPort. You can do this with System.setProperty(), or from the command line with the -D syntax. EDIT: per comment, set https.proxyPort and https.proxyHost for HTTPS.


Proxies are supported through two system properties: http.proxyHost and http.proxyPort. They must be set to the proxy server and port respectively. The following basic example illustrates it:

String url = "http://www.google.com/",
       proxy = "proxy.mydomain.com",
       port = "8080";
URL server = new URL(url);
Properties systemProperties = System.getProperties();
systemProperties.setProperty("http.proxyHost",proxy);
systemProperties.setProperty("http.proxyPort",port);
HttpURLConnection connection = (HttpURLConnection)server.openConnection();
connection.connect();
InputStream in = connection.getInputStream();
readResponse(in);

You can also set

-Djava.net.useSystemProxies=true

On Windows and Linux this will use the system settings so you don't need to repeat yourself (DRY)

http://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html#Proxies


Set following before you openConnection,

System.setProperty("http.proxyHost", "host");
System.setProperty("http.proxyPort", "port_number");

If proxy requires authentication,

System.setProperty("http.proxyUser", "user");
System.setProperty("http.proxyPassword", "password");

For Java 1.8 and higher you must set -Djdk.http.auth.tunneling.disabledSchemes= to make proxies with Basic Authorization working with https.