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:
![android_http_apache_client_cookie android_http_apache_client_cookie](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_t__zTjWWFv8ptP_KCdqMizTVK434nVkd0tE8hVhXQoV6CvPJq8meksE21VAv8HB4UB2LwZI4R6_eg8v85NmU7qEop_TRoaOriHFAUAW88LbxE8CFjZ8PAIUpJcApFgGsC6jj_Y6ey-eYE7GkyqAtzH9y_LiANPG6oaIAgDyW_t17NfcGZcEQbdqZ3QNw=s0-d)
| ![android_http_apache_client_server_cookie android_http_apache_client_server_cookie](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_srD9EXUiXbl2zxRBBYolZdts1R9HEMFHclv2V_47DlvMHsIUw0pyViCc9Qyj2irhSH7KCafJM60XKtjHJj5hFM_XGepqWncTvlBleeSSlpabexonZm_h3ZJ012onybmaHgHtaoyIEuLbvXPWsV0hod7vMJfsES1Nu79tlXJgmiKDB9_IWY0O4P447kwBBdpTJuyWs=s0-d) |
Client side cookie output | Server side cookie output |
Source code available at
github.
No comments:
Post a Comment