Android HttpClient persistent cookies

Knossos picture Knossos · Nov 10, 2010 · Viewed 19.6k times · Source

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?

Answer

Aaron Saunders picture Aaron Saunders · Nov 10, 2010

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);