Connect to the net through a proxy server in Java

An applet will automatically use the browser settings. With an application, the proxy server can be specified with the following properties: proxySet, proxyHost and proxyPort.

They can either be set at the command line or in the source.

At command line:

java -DproxySet=true -DproxyHost=proxyserver.come -DproxyPort=80 Main

In source:

import java.util.Properties;


Properties props = System.getProperties();
props.put("proxySet", "true");
props.put("proxyHost", "");
props.put("proxyPort", "80");

It could be that the proxy server requires you to authenticate with a username + password. This request has to be in the form “username:password” encoded in base64. A converter to base64 can be found in the package sun.misc – BASE64Encoder. The final call is to setRequestProperty which will change the http header as to get you through the proxy.
Code snippet:

   import sun.misc.*;

   URL url = new URL("");
   URLConnection connection = url.openConnection();

   String authReq = "myusername:mypassword";   // replace myusername and mypassword
   B64Encoder = new BASE64Encoder();

   String encodedAuthReq = B64Encoder.encode(authReq.getBytes());

   connection.setRequestProperty("Proxy-Authorization", "basic " + encodedAuthReq);