Java Tip: Basic Authentication with HttpURLConnection

By Angsuman Chakraborty, Gaea News Network
Friday, July 6, 2007

Java provides a super simple, yet hidden from plain view, way to do basic authentication of HttpURLConnection / URLConnection.

Before making a connection add the following lines of code:


final String login ="...";
final String password ="...";

Authenticator.setDefault(new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication (login, password.toCharArray());
    }
});

This sets your default Authenticator which is called whenever authentication is required for any URLConnection. Problem solved.

Note: final is required for the inner class to access the variable.

Authenticator is available since JDK 1.2 and yet very few information is there about it on the web. Almost everyone recommend using a class from Sun package ( sun.misc.BASE64Encoder() ) and do the encoding manually. None of this is required in the simple solution above.

The Java URLConnection API should have a setAuthenticator(Authenticator) method for making it easier to use this class in multi-threaded context where authentication is required.

Discussion
January 6, 2010: 6:53 am

Watch TV shows online free, including sports TV, news TV, and movies online. Spreety TV online is your free guide of online TV

November 17, 2009: 1:33 pm

This is a great idea, however, as you point out, it’s relatively difficult to get working correctly in a multithreaded fashion.

I was being lazy and attempted to use something like this in a JSP page–it was quite disastrous since the default authenticator would not use any other credentials; using it in a servlet container (particularly being lazy and in jsp) requires a lot more thought.


Joaquin
November 10, 2009: 6:40 pm

Thanks. This really help me. I was searching for a solution like this, because I tried a lot with other solutions but this works fine.

YOUR VIEW POINT
NAME : (REQUIRED)
MAIL : (REQUIRED)
will not be displayed
WEBSITE : (OPTIONAL)
YOUR
COMMENT :