Enterprise J2ME Developing Mobile Java Applications [Electronic resources]

Michael Juntao Yuan

نسخه متنی -صفحه : 204/ 59
نمايش فراداده

6.4 HTTP Basic Authentication

Some HTTP headers can carry client credential information. Those credentials are used by servers to determine the client's identity and then grant or deny access to the requested resources. In the HTTP basic authentication scheme, the client sends its username and password in plain text with every request. The procedure is the following:

Use the Base64 algorithm to encode a username : password string

Send the encoded string and string Basic in the HTTP header Authorization

For example, if the username is Aladdin and password is open sesame, the HTTP authentication header is the following.

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

6.4.1 Code Example

To enable HTTP basic authentication in the HttpClient class, we need to plug in a handler (BasicAuthHandler). We can easily use BasicAuthHandler together with CookieHandler to make the HttpClient object keep track of a client session over an authentication connection (Listing 6.6).

Listing 6.6. Use cookies with HTTP basic authentication

HttpClient client = new HttpClient ();
Handler h1 = new CookieHandler();
Handler h2 = new BasicAuthHandler(user, pass);
client.addHandler( h1 );
client.addHandler( h2 );
client.setUrl( url );
client.setRequestMethod( HttpConnection.GET );
byte [] result = client.query(null);

Sample source code for the BasicAuthHandler class is shown in Listing 6.7.

Listing 6.7. The BasicAuthHandler class
public class BasicAuthHandler implements Handler {
private String username;
private String password;
public BasicAuthHandler (String u, String p) {
username = u;
password = p;
}
public void prepareHeaders(HttpConnection c) throws Exception {
String s = encode(username + ":" + password);
c.setRequestProperty("Authorization", "Basic " + s);
}
public boolean processHeaders(HttpConnection c) throws Exception {
// Do nothing.
return false;
}
// Base64 encoding.
//
// This implementation is adopted from
// Kenneth Ballard's HttpClient package.
// Released under LGPL.
private String encode(String d) {
// Implementation details skipped
}
}