Basic HTTP authentication with Java

Opening a URL in Java is pretty much straightforward by using the class. If the URL trying to be accessed is password protected (by Apache’s AuthType for example), you will need to authenticate before trying to open the URL. The easiest way to authenticate is by using the Authenticator ( class which is available on Java 1.2 and higher:

final String theUsername = username;
final String thePassword = password;

Authenticator.setDefault(new Authenticator() {
     protected PasswordAuthentication getPasswordAuthentication() {
           return new PasswordAuthentication(theUsername, thePassword.toCharArray());

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s