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());