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.
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().
URL url = new URL(urlToConnect); HttpURLConnection httpUrlConnection = (HttpURLConnection) url. openConnection(); Step 2: Add headers to the HttpURLConnection using setRequestProperty method.
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.
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();
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With