How to keep HTTP session cookies in HttpContext between activities on Android?

uzer picture uzer · May 24, 2012 · Viewed 11.5k times · Source

Here is current simple description my app. It uses some remote server API, which uses standart HTTP session. Login activity. It calls auth class, passing login and password.

public class Auth extends AsyncTask{
...
private DefaultHttpClient client = new DefaultHttpClient();
private HttpContext localContext = new BasicHttpContext();
private CookieStore cookieStore = new BasicCookieStore();
...
public void auth(String login, String password) {
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    HttpPost request = new HttpPost(url);
    ...
}
protected void onPostExecute(Boolean result){
    parent.loginresponse(result)
}

On successful auth, remote server creates standart HTTP session, sending me cookie, saved in CookiStore. After login, loginresponse starts main activity. There I wish to have one universal class for all API requests.

How do I make correct keeping alive HTTP session information, created after login, between all activities, and passing it to needed functions for corresponding API methods?

Answer

OrhanC1 picture OrhanC1 · Nov 28, 2014

If you use a DI framework like Dagger, you can maintain a HttpContext between activities and inject it wherever you like!