Basic HTTP authentication with Java

Opening a URL in Java is pretty much straightforward by using the java.net.URL 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 (java.net.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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s