Basic HTTP authentication in MIDlet

RSS Reader v1.1There was one feature request made for my RSS Reader application. It was suggested that the application should support basic authentication like the one you get with the htaccess file. The feature was actually a lot easier to implement then I thought in the first place. With a few google searchs I found a specifications for the RFC 2617, “HTTP Authentication: Basic and Digest Access Authentication”.
What this means in practice is that application would need to send an authorization header with the HTTP request. Here is an example of the authorization header:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

The string “QWxhZGRpbjpvcGVuIHNlc2FtZQ==” is base64 encoded string that contains the username and password separated by a single colon (username:password). Here is a sample code how to do this with the HttpConnection:

HttpConnection hc = (HttpConnection) url );
/** Some web servers requires these properties */
“Profile/MIDP-1.0 Configuration/CLDC-1.0″);
hc.setRequestProperty(“Content-Length”, “0”);
hc.setRequestProperty(“Connection”, “close”);

Add authentication header in HTTP request. Basic authentication should be formatted like this:
Authorization: Basic QWRtaW46Zm9vYmFy
String username = “jack”;
String password = “secret”;
Base64 b64 = new Base64();
String userPass;
userPass = username + “:” + password;
userPass = b64.encode(userPass.getBytes());
hc.setRequestProperty(“Authorization”, “Basic ” + userPass);

You download binaries and the source code for the RSS Reader v1.1 application from RSS Reader MIDlet page. The new version includes the basic authentication and few bug fixes.