How can I make a URL connection through a proxy if the proxy server requires login information (user name, password)?

Tim Rohaly

To have your URLConnection object use a proxy, you will first need to set some system properties:

Properties properties = System.getProperties();
properties.put("http.proxyHost", "my.proxyhost.com");
properties.put("http.proxyPort", "1234");
where you should use the fully-qualified domain name of your proxy host in place of "my.proxyhost.com" and your proxy's port number in place of "1234".

If your proxy server requires user name/password authentication you need to insert this login information into the HTTP header by invoking the setRequestProperty() method of the URLConnection. The HTTP protocol requires that the user name/password combination be Base64 encoded. This is not encryption - it is simply a way of representing ASCII characters using a reduced character set for portability.

The Java 2 platform does not include classes to perform the Base64 encoding, so you will have to write your own or use one of the many publicly-available ones. In the following example I use one written by Chuck McManis, which you can get from http://www.mcmanis.com/~cmcmanis/java/encoders/index.html:
URL url = new URL("www.jGuru.com");
URLConnection connection = url.openConnection();
String login = "username:password";
String encodedLogin = new BASE64Encoder().encodeBuffer(login.getBytes());
connection.setRequestProperty("Proxy-Authorization", "Basic " + encodedLogin);
This should establish the URL connection, which you can then use however you like.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact