I have a an app that should send a GET request to a URL and send some cookies along with it. I've been looking at a few code examples for BasicCookieStore and Cookie classes, but I'm not able to figure out how to use them. Can anyone point me in the right direction?
Asked
Active
Viewed 3,621 times
1 Answers
2
To use cookies you need something along the lines of:
CookieStore cookieStore = new BasicCookieStore();
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpContext ctx = new BasicHttpContext();
ctx.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet get = new HttpGet("your URL here");
HttpResponse response = httpclient.execute(get,ctx);
And if you want to keep cookies between requests, you have to reuse cookieStore and ctx for every request.
Also, you may read your cookieStore to see what's inside:
List<Cookie> cookies = cookieStore.getCookies();
if( !cookies.isEmpty() ){
for (Cookie cookie : cookies){
String cookieString = cookie.getName() + " : " + cookie.getValue();
Log.info(TAG, cookieString);
}
}
lenik
- 23,228
- 4
- 34
- 43
-
Maybe I have not fully understood the concept of cookies, but i have a two strings which I want to send to the url as name-value pairs. From this code, I can't understand how to do that. Could you please guide me? – Rameez Hussain Nov 25 '12 at 23:56
-
@RameezHussain you may use `addCookie()` method of `CookieStore`: http://developer.android.com/reference/org/apache/http/client/CookieStore.html – lenik Nov 25 '12 at 23:58