Wednesday, November 13, 2013

Exchange Cookie

Exchange Cookie

One interesting aspect in HTTP protocol is the cookie management. As we know HTTP is a stateless protocol so using cookies we can persist some information across HTTP requests. As example we can suppose to make two HTTP request: one where we invoke a URL and the server returns a cookie containing some information and another one where we send back to the server the cookie.
The first request is very simple:
1HttpPost post = new HttpPost(url);
2HttpResponse resp = client.execute(post);
Then we read the cookie (line 1,3):
01CookieStore store = ((DefaultHttpClient) client).getCookieStore();
02 
03List<Cookie> cookies = store.getCookies();
04if (cookies != null) {
05    for (Cookie c : cookies) {
06        System.out.println("Name ["+c.getName()+"] - Val ["+c.getValue()+"]
07                      - Domain ["+c.getDomain()+"] - Path ["+c.getPath()+"]");
08        store.addCookie(c);
09    }
10}
At line 1 we simply get the cookie store where the cookies are stored. At line 3 we retrieves the cookies list. In the second post request we have to maintain the cookie we retrieved in the first request so we have:
1HttpContext ctx = new BasicHttpContext();
2ctx.setAttribute(ClientContext.COOKIE_STORE, store);
3 
4// Post again with cookie
5HttpPost post1 = new HttpPost(url);
6client.execute(post1);
7HttpResponse resp1 = client.execute(post, ctx);
At line 1 we create BasicHttpContext to handle cookies and at line 2 we set the store inside our context and finally at line 7 we execute the request passing the context too.
One thing we have to notice is that the DefaultHttpClient is always the same so that we can re-use the cookies.
Running the example we have:
android_http_apache_client_cookie


android_http_apache_client_server_cookie
Client side cookie outputServer side cookie output
 
 



Source code available at github.

No comments:

Post a Comment