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.
-
public class BasicAuthenticator
-
-
private String username;
-
private char[] password;
-
-
-
this.username = username;
-
this.password = password.toCharArray();
-
}
-
-
@Override
-
protected PasswordAuthentication
-
getPasswordAuthentication() {
-
-
password);
-
}
-
}
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:
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