How to handle HTTP authentication using HttpURLConnection?

Opher picture Opher · Feb 3, 2011 · Viewed 82.6k times · Source

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.

Answer

Bruno De Fraine picture Bruno De Fraine · Feb 3, 2011

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