Handling HTTP authentication in Java

Google Chrome (Ubuntu 9.10)

Microsoft IE 8 (Windows XP)

Most of us might have got this pop up when we browse through some websites – especially in intranets. And it’s perfectly fine for the administrator (a.k.a. webmaster) to put such restrictions on users to enhance the information security. Because that’s what a security engineer is expected to do !

But what if we have to access the resource through our Java code? How to we handle that? I have faced this issue when I was writing a module to crawl through a secured website using HTTPunit.

We just need to set the Authorization header with the Base64 encoded username and password. Here is a sample code:

String usernameAndPassword = "myUsername" + ":" + "myPa$$word";
String encodedString = new sun.misc.BASE64Encoder().encode (usernameAndPassword.getBytes());
httpConnection.setRequestProperty("Authorization", "Basic " + encodedString);

How Base 64 encoding works?

Advertisements