Categories
programming

Manage Cookies with BlackBerry Java

When interacting with [generally and widely interpreted] web services, you may be required to communicate state (usually a login authentication token). This [usually] takes the form of a cookie and in our interconnected wide world of interwebs, browsers handle cookies just fine; custom-built clients not always. On the BlackBerry, if you’re putting together a Java app, and using the HttpConnection class to communicate with said server, you need to manage that cookie (and hence state) by yourself. Fortunately, it’s not rocket science.

The basic workflow is: you connect to the endpoint and POST some data. On the response, you need to read the headers and look for the “Set-Cookie” field. From that value, you can extra the data you need. On all subsequent requests, you set the “Cookie” field on the header. Simple. Time for some code.

NOTE: Exception handling omitted for brevity and readability.

The first request is just a regular POST in this instance. The buffer variable is a byte[].

HttpConnectionFactory factory = new HttpConnectionFactory(endpoint);
HttpConnection connection = factory.getNextConnection();
connection.setRequestProperty("User-Agent", "BlackBerry Client");
connection.setRequestProperty("Accept", "*/*");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod(HttpConnection.POST);
OutputStream output = connection.openOutputStream();
output.write(buffer);

From that request, we wait for the response and read that. In this example, I am looking for the PHPSESSID field that was set as part of the response in the header.

String cookie = connection.getHeaderField("Set-Cookie");
if(null != cookie) {
  int php = cookie.indexOf("PHPSESSID=");
    if(0 <= php) {
      php += "PHPSESSID=".length();
      int term = cookie.indexOf(";", php);
      if(0 <= term) {
        _session = cookie.substring(php, term);
      }
  }
}

Now I have the token required (cookie) that I can now send on every subsequent request. The code for that is for all intensive purpose, the same as the first code snippet with one additional line:

connection.setRequestProperty("Cookie", "PHPSESSID=" + _session + ";");

The order of the setting of the request properties won’t make a difference, so just use that anywhere before you open the output stream for writing.

One reply on “Manage Cookies with BlackBerry Java”

Comments are closed.