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:
1 | HttpPost post = new HttpPost(url); |
2 | HttpResponse resp = client.execute(post); |
Then we read the cookie (line 1,3):
01 | CookieStore store = ((DefaultHttpClient) client).getCookieStore(); |
03 | List<Cookie> cookies = store.getCookies(); |
05 | for (Cookie c : cookies) { |
06 | System.out.println( "Name [" +c.getName()+ "] - Val [" +c.getValue()+"] |
07 | - Domain [ "+c.getDomain()+" ] - Path [ "+c.getPath()+" ]"); |
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:
1 | HttpContext ctx = new BasicHttpContext(); |
2 | ctx.setAttribute(ClientContext.COOKIE_STORE, store); |
5 | HttpPost post1 = new HttpPost(url); |
7 | HttpResponse 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:
| |
Client side cookie output | Server side cookie output |
No comments:
Post a Comment