Jake alfred
Jake alfred

Reputation: 19

How to stay logged in / maintain cookie session?

Im working on an android application that sends a post request with a username and password to a server and I successfully get the correct response back. However, when I try to click on a button that sends another post request after I logged in, I get a message back from the server saying that im not logged in. I know this has to do with storing cookies, can someone help me out with doing that? Here is the html client code:

    public class SimpleHttpClient {

  private static HttpClient mHttpClient;


    private static HttpClient getHttpClient() {
    if (mHttpClient == null) {
        mHttpClient = new DefaultHttpClient();
        final HttpParams params = mHttpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
        ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
    }
    return mHttpClient;
}


public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
    BufferedReader in = null;
    try {
        HttpClient client = getHttpClient();
        HttpPost request = new HttpPost(url);
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
        request.setEntity(formEntity);
        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();

        String result = sb.toString();
        return result;
    }
    finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Upvotes: 1

Views: 466

Answers (1)

Sarah Caixeta
Sarah Caixeta

Reputation: 31

I had the same issue some time ago.
You can serialize the Cookies in CookieStore and save it somewhere when you login.

httpclient.execute(//login);
CookieStore cookieStore = httpclient.getCookieStore();
saveCookieData(cookieStore);

Before you make the post request, you deserialize it, and set it to the http client.

httpclient.setCookieStore(retrieveCookieStore());

Upvotes: 1

Related Questions