Android HttpClient persistent cookies
Solution 1
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);
Solution 2
Don't create new HttpClients; this will clear the cookies. Reuse a single HttpClient.
Solution 3
Make your httpClient a singleton class.
Solution 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;
Knossos
A senior software developer designing primarily Android based applications.
Updated on June 05, 2022Comments
-
Knossos almost 2 years
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 over 13 yearsThanks for the information, that seems to be the best choice for me.
-
DagW almost 11 yearsYou 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.
-
Senthil almost 11 yearsso can i make the httpclient as static.
-
Emmanuel almost 11 years@vsk: Yes. You could, for example, use a Singleton. I typically create a ConnectionHelper Singleton where I can serialize requests to the server.