Friday, 11 May 2012

Session maintenance using cookies.

Session maintenance using cookies.

In this post i am going to explain how to retrieve and save cookies from the HTTP Post request and send it further with HTTP Get requests.

Retrieving and storing cookies:

Suppose you have a login web service and after successfully authenticating the server provides you with a cookie then following snippet can be used to retrieve and store the cookies.

DefaultHttpClient httpclient = new DefaultHttpClient();HttpPost httppost = new HttpPost(URL);httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);  nameValuePairs.add(new BasicNameValuePair("username", YOUR_USERNAME));nameValuePairs.add(new BasicNameValuePair("password",YOUR_PASSWORD);httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  HttpResponse httpResponse = null;httpResponse = httpclient.execute(httppost);
           List<Cookie> cookies = httpclient.getCookieStore().getCookies(); //  Storing cookies
cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None");//No cookie found } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); // Cookie found 
} }

Now you have retrieved cookies and stored them in the Array List.
Cookie has various parts as follows:
1.Session ID.
2.Cookie name.
3.Domain etc...

Save the required fields from in preferences of cookie store so that you can resend these cookies to get requests to make other services call.

Sending cookies to make other web services calls:

Now you can send these cookies along with the get requests to make other web services calls.
Following snippet shows how to do it.

HttpClient httpclient = new DefaultHttpClient();HttpGet httpget = new HttpGet(url);HttpResponse response;COOKIE_VALUE=PreferenceConnector.readString(activity, PreferenceConnector.COOKIE_SESSION_ID, null); //I had stored the cookies in Prefrences and was retrieving the cookie session ID from there. 
httpget.setHeader("Cookie",  "JSESSIONID="+COOKIE_VALUE); //Here i am sending the Cookie session ID try { response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); RESULT_FINAL = convertStreamToString(instream); instream.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }