Using java.net.Authenticator for Proxy-Authentication
June 9th, 2008 Mario Hochreiter
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?
Entry Filed under: Java
2 Comments Add your own
1. Handset application proxy&hellip | July 15th, 2008 at 8:45 am
[…] I’ve read in java you can use the Authenticator class to handle this. There are a few examples here and here. My Code: […]
2. Handset application Authe&hellip | July 15th, 2008 at 8:52 am
[…] I’ve read in java you can use the Authenticator class to handle this. There are a few examples here and here. My Code: […]
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed