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", "proxyserver.com");
props.put("proxyPort", "80");
System.setProperties(props);

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("http://www.yahoo.com");
   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);