Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 634
Opher Avatar asked Feb 03 '11 06:02

Opher


People also ask

How do I set authentication in HttpURLConnection?

As mentioned previously, we have to use “Authorization” as our header and “Basic ” + encoded credentials as our value: connection. setRequestProperty("Authorization", authHeaderValue); Finally, we need to actually send the HTTP request, like for example by calling getResponseCode().

How do I pass HttpURLConnection header?

URL url = new URL(urlToConnect); HttpURLConnection httpUrlConnection = (HttpURLConnection) url. openConnection(); Step 2: Add headers to the HttpURLConnection using setRequestProperty method.

How do you authorize a URL in Java?

The setAuthenticator(Authenticator auth) is a method of Java HttpURLConnection class. This method is used to set the authentication request through HTTP protocol. If no authentication is sent then default authentication is used.


2 Answers

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(); 
like image 161
Bruno De Fraine Avatar answered Oct 11 '22 21:10

Bruno De Fraine


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!

like image 39
lboix Avatar answered Oct 11 '22 23:10

lboix