Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android HttpClient persistent cookies

UPDATE: This question and its answers should no longer be recommended to anyone reading this. Android no-longer recommends HttpClient (read: deprecated), and instead recommends HttpUrlConnection. A good example of libraries to use now, are Retrofit and OkHttp. In the context of this question, cookies can be saved, stored and delivered with subsequent queries. This is not handled transparently. With OkHttp you can use Interceptors.

I have an Android application with multiple intents.

The first intent is a login form, subsequent intents rely on cookies provided from the login process.

The problem that I am having is that cookies do not appear to be persisting across the intents. I am creating new HttpClients in each intent (I initially tried to Parcelable transmit it across to each intent, which did not work so well).

Does anyone have any tips for making cookies persist across intents?

like image 568
Knossos Avatar asked Nov 10 '10 16:11

Knossos


2 Answers

You can do what @Emmanuel suggested or you can pass the BasicHttpContext between the HttpClients you are creating.

Example Use of context and cookies, complete code here

    HttpClient httpclient = new DefaultHttpClient();      // Create a local instance of cookie store     CookieStore cookieStore = new BasicCookieStore();      // Create local HTTP context     HttpContext localContext = new BasicHttpContext();     // Bind custom cookie store to the local context     localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);      HttpGet httpget = new HttpGet("http://www.google.com/", localContext); 
like image 114
Aaron Saunders Avatar answered Sep 29 '22 11:09

Aaron Saunders


Don't create new HttpClients; this will clear the cookies. Reuse a single HttpClient.

like image 22
Emmanuel Avatar answered Sep 29 '22 11:09

Emmanuel