Archive for June 9th, 2008

Using java.net.Authenticator for Proxy-Authentication

The company i am currently writing code for uses a proxy for outgoing network calls. The proxy requires a username and password to let you connect to the outside world. So far so good. To connect through the proxy in my Java application first i tried to set the following properties, as suggested in some forums:

  • http.proxyHost=proxyHost
  • http.proxyPort=proxyPort
  • http.proxyUserName=username
  • http.proxyPassword=pass

But this didn't work. I always got the HTTP error 407 which means Proxy authentication required. Reading Suns documentation for the possible proxy properties to my surprise showed that http.proxyUserName and http.proxyPassword are not listed as possible properties.

java.net.Authenticator to the rescue! The class Authenticator represents an object that knows how to obtain authentication for a network connection. Usually, it will do this by prompting the user for information. For a detailed description see the javadoc.

To get things working first we need to subclass Authenticator.

JAVA:
  1. public class BasicAuthenticator
  2.   extends Authenticator {
  3.  
  4.   private String username;
  5.   private char[] password;
  6.    
  7.   public BasicAuthenticator(String username,
  8.     String password) {
  9.    
  10.     this.username = username;
  11.     this.password = password.toCharArray();
  12.   }
  13.    
  14.   @Override
  15.     getPasswordAuthentication() {
  16.    
  17.     return new PasswordAuthentication(username,
  18.       password);
  19.   }
  20. }

The only thing that needs to be done is to override the getPasswordAuthentication method and return a PasswordAuthentication object with username and password character array.
This implementation has to be set as default:

JAVA:
  1. Authenticator.setDefault(new BasicAuthenticator("user","pass"));

In combination with correclty set http.proxyHost and http.proxyPort the authentication works like a charm, also for Proxies.
Now i can connect to the outside world, but still doesn't know why the properties http.proxyPassword and http.proxyUserName are not working for me... Any ideas?

3 comments June 9th, 2008


Calendar

June 2008
M T W T F S S
« Mar    
 1
2345678
9101112131415
16171819202122
23242526272829
30  

Posts by Month

Posts by Category