Opher
Opher

Reputation: 525

How to handle HTTP authentication using HttpURLConnection?

I'm writing a Java client that POSTs to a HTTP server that requires authentication.
I have to support at least the following three authentication methods: Basic, Digest or Negotiate. Additionally the POST may be very large (over 2MB), so I need to use streaming. As is documented for HttpURLConnection

When output streaming is enabled, authentication and redirection cannot be handled automatically. A HttpRetryException will be thrown when reading the response if authentication or redirection are required.

So, I need to handle authentication myself. I searched, and searched again, for a way to employ the, already coded, classes - but found no way...

I could just pluck the needed sources from here (as they are GPLv2 with Classpath exception). Is this the right way?

Thanks.

Upvotes: 33

Views: 86789

Answers (2)

Bruno De Fraine
Bruno De Fraine

Reputation: 47316

Do you need output streaming? The HttpURLConnection most definitely supports authentication with the Authenticator class, see: Http Authentication.

Update: In case the Authenticator is not an option, you can manually do HTTP basic authentication by adding an extra header to your HTTP request. Try the following code (untested):

String userPassword = username + ":" + password;
String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
URLConnection uc = url.openConnection();
uc.setRequestProperty("Authorization", "Basic " + encoding);
uc.connect();

Upvotes: 49

Lucien Boix
Lucien Boix

Reputation: 1009

Related to @Mat's comment :

Here is an example used by my team and I :

import org.apache.commons.codec.binary.Base64;

HttpGet getRequest = new HttpGet(endpoint);
getRequest.addHeader("Authorization", "Basic " + getBasicAuthenticationEncoding());

private String getBasicAuthenticationEncoding() {

        String userPassword = username + ":" + password;
        return new String(Base64.encodeBase64(userPassword.getBytes()));
    }

Hope it helps!

Upvotes: 4

Related Questions