uzer
uzer

Reputation: 160

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

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?

Upvotes: 7

Views: 11937

Answers (3)

John Doe
John Doe

Reputation: 403

You can use a singleton class that would look something like this:

public class UserSession
{
    private static UserSession sUserSession;

    /*
       The rest of your class declarations...
    */

    public get(){
        if (sUserSession == null)
        {
            sUserSession = new UserSession();
        }
        return sUserSession;
    }
}

Once an instance of this class is initialized, it will stay in memory.

Upvotes: 1

OrhanC1
OrhanC1

Reputation: 1410

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

Upvotes: 1

nikki
nikki

Reputation: 3228

You can do something like the following:

HttpClient client = getNewHttpClient();
        // 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);
        try {
            request = new HttpPost(url);
            // request.addHeader("Accept-Encoding", "gzip");
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (postParameters != null && postParameters.isEmpty() == false) {

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                    postParameters.size());
            String k, v;
            Iterator<String> itKeys = postParameters.keySet().iterator();
            while (itKeys.hasNext()) {
                k = itKeys.next();
                v = postParameters.get(k);
                nameValuePairs.add(new BasicNameValuePair(k, v));
            }

            UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(
                    nameValuePairs);
            request.setEntity(urlEntity);

        }
        try {

            Response = client.execute(request, localContext);
            HttpEntity entity = Response.getEntity();
            int statusCode = Response.getStatusLine().getStatusCode();
            Log.i(TAG, "" + statusCode);

            Log.i(TAG, "------------------------------------------------");

            if (entity != null) {
                Log.i(TAG,
                        "Response content length:" + entity.getContentLength());

            }
            List<Cookie> cookies = cookieStore.getCookies();
            for (int i = 0; i < cookies.size(); i++) {
                Log.i(TAG, "Local cookie: " + cookies.get(i));

            }

            try {
                InputStream in = (InputStream) entity.getContent();
                // Header contentEncoding =
                // Response.getFirstHeader("Content-Encoding");
                /*
                 * if (contentEncoding != null &&
                 * contentEncoding.getValue().equalsIgnoreCase("gzip")) { in =
                 * new GZIPInputStream(in); }
                 */
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(in));
                StringBuilder str = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {

                    Log.i(TAG, "" + str.append(line + "\n"));
                }
                in.close();
                response = str.toString();
                Log.i(TAG, "response" + response);
            } catch (IllegalStateException exc) {

                exc.printStackTrace();
            }

        } catch (Exception e) {

            Log.e("log_tag", "Error in http connection " + response);

        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            // client.getConnectionManager().shutdown();
        }

        return response;
    enter code here

Upvotes: 0

Related Questions