Wednesday, 2010-12-29

» Preemptive HTTP Authentication with Android 2.2

Preemptive HTTP Authentication with Android 2.2

I just spend a good few hours trying to figure out why my Android application fails to communicate with a web service which requires preemptive Basic HTTP Authentication. Here’s an example code for anyone else on the same quest:

String auth = android.util.Base64.encodeToString(
	(username + ":" + password).getBytes("UTF-8"), 
	android.util.Base64.NO_WRAP
);
HttpGet request = new HttpGet(url);
request.addHeader("Authorization", "Basic "+ auth);

Thanks Mark Murphy.

David Linsin shows in his blog how to use HttpRequestInterceptor to fiddle with the request before it is sent. For some reason I wasn’t able to make it work and I don’t see any reason why adding the Authorization header manually wouldn’t be enough. Feel free to correct me if I’m missing something here.

Android 2.2 ships with Base64 utility class. With older versions you can use http://iharder.net/base64. This is what Mark Murphy uses in his examples. The interface is almost identical.

android.util.Log Trims, Base64 Doesn’t!

This is actually the reason why all this took so long to figure out. The web server returned “400 Bad Request” and I couldn’t figure out what was wrong. I knew the problem was in the Authorization header but when I logged the authorization token everything looked OK… until I did this:

Log.i("AUTH", "\""+auth+"\"");

I turned out that the base64 encoded authorization token had an extra newline at the end. Hence, android.util.Base64.NO_WRAP.

Tags

Comments (View)
blog comments powered by Disqus