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.