37

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?

Knossos
  • 15,802
  • 10
  • 54
  • 91
  • Incidentally, the closest I have found is to write out the cookiestore into shared prefs. – Knossos Nov 10 '10 at 17:04
  • To end this discussion, I succeeded in my quest by creating my own HttpClient class with methods to set and get its CookieStore. I made it so that on initializing the client it automatically retrieved all cookies from SharedPreferences. Also, before each time a new Intent is created or the current one is finished, all cookies are copied into SharedPreferences. – Knossos Nov 16 '10 at 14:29

4 Answers4

31

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);
www.jensolsson.se
  • 3,023
  • 2
  • 35
  • 65
Aaron Saunders
  • 33,180
  • 5
  • 60
  • 80
22

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

Emmanuel
  • 16,791
  • 6
  • 48
  • 74
4

define HttpClient in Application class, and use it in activity.

in Application

public class AAA extends Application {
    public HttpClient httpClient; 

    httpClient = new DefaultHttpClient(); 

in Activity

AAA aaa = (AAA)getApplication();
httpClient = app.httpClient;
panicstyle
  • 101
  • 8
  • You have no control over the state of the application, if you use this make sure to do a null-check or a method in AAA to get the Client with this check. – DagW May 21 '13 at 09:14
4

Make your httpClient a singleton class.

sebataz
  • 1,025
  • 2
  • 11
  • 35
user569873
  • 424
  • 5
  • 13