user703834
user703834

Reputation: 93

Android Cookie Storage

In my android app i want to maintain the session id for at least 30 days even if the app quits. I am using DefaultHttpClient. When i send first request to the server it returns session id, i have to use this returned session id for all other request.

Upvotes: 2

Views: 599

Answers (2)

Vipin Sahu
Vipin Sahu

Reputation: 1451

Right U can save your Session ID in SharedPref, However there are other value that need to be saved , if your cookies expires u can relogin again with same credential again , other wise u can use persistence cookies (becoz user can kill the apps anytime ), below code snippets is only for till user used app (user does kill the app process )

     private static CookieStore cookieStore = new BasicCookieStore();


        InputStream is = null;
        try {

            final DefaultHttpClient httpClient = new DefaultHttpClient();
            httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

            Log.d("vipin", url.toString());

            HttpPost httpPost = new HttpPost(url);
            /** maintain session if logged in */
            if (SouqApplication.getBooleanValue(Constants.IS_LOGGED_IN))
                httpPost.setHeader(Constants.PHPSESSID, SouqApplication.getStringValue(Constants.SESSION_ID));
            //httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            HttpContext localContext = new BasicHttpContext();
            localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
            httpClient.setCookieStore(cookieStore);
            HttpResponse httpResponse = httpClient.execute(httpPost, localContext);
            setCookies(httpClient.getCookieStore().getCookies());
            HttpEntity httpEntity = httpResponse.getEntity();
            String errorHandlling = EntityUtils.toString(httpEntity);

            return errorHandlling ;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

And for a Better approach U can use a ready cake popular library Persistent Cookie Storage with PersistentCookieStore http://loopj.com/android-async-http/

Upvotes: 0

Haphazard
Haphazard

Reputation: 10948

You can set a Shared Preference to maintain your session ID. You can use a second pref to store the date of the last connection so you are able to reset the session ID after 30 days of inactivity.

Upvotes: 2

Related Questions