Android HTTP Cookies [JSESSIONID]

I explained how to set HTTP POST Parameters in my last post.  There I discussed about using the DefaultHttpClient provided in the Android package.

Now I would like to explain how you can get the cookies form the HTTP Response and send them back in the Request.

With the HTTP client you can ask for cookies using getCookieStore() method as show below.
List<Cookie> cookies = httpclient.getCookieStore().getCookies();

you can process the list of cookies using the below snippet.

if (cookies.isEmpty()) {
    System.out.println("None");
} else {
    for (int i = 0; i < cookies.size(); i++) {
        Cookie cookie = cookies.get(i);
        if(cookie.getName().equals("JSESSIONID")){
            jSessionid = cookie.getValue();
            Log.i("Cookies","- " + cookies.get(i).toString());
            break;
        }
    }
}

Here I am looking for JSESSIONID how ever you can look for PHPSESSIONID or any cookie that you want.

I used a member variable called “jSessionid” in order to store the session id and resend it with each request. I store the jSessionID, through it guaranteed to stay the same, every time I get the response in case the redirection happens between 2 web servers [this is for one of odd cases where I am not controlling the Web response]

Here is my complete getResponseMethod().

private HttpResponse getResponse(HttpPost post) throws ClientProtocolException, IOException{
       
        DefaultHttpClient httpclient = getDefaultClient();
        HttpResponse response = null;
        try{
            post.setHeader(“Cookie”, “JSESSIONID=”+jSessionid);
            response = httpclient.execute(post);
           
            HttpEntity entity = response.getEntity();
            entity.consumeContent();
            List<Cookie> cookies = httpclient.getCookieStore().getCookies();
            if (cookies.isEmpty()) {
                System.out.println(“None”);
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    Cookie cookie = cookies.get(i);
                    if(cookie.getName().equals(“JSESSIONID”)){
                        jSessionid = cookie.getValue();
                        Log.i(“Cookies”,”- ” + cookies.get(i).toString());
                        break;
                    }
                }
            }
        }finally{
                // When HttpClient instance is no longer needed,
                // shut down the connection manager to ensure
                // immediate deallocation of all system resources
                httpclient.getConnectionManager().shutdown();
        }
        return response;
    }