9

I would like to preserve a session while connecting to server using HttpGet and I need to understand how it handles cookies.

The server developer says that he handles all cookies stuff by himself. I use HttpGet request to access the server as follows: InputStream isResponse = null;

    HttpGet httpget = new HttpGet(strUrl);
    HttpResponse response = mClient.execute(httpget);

    HttpEntity entity = response.getEntity();
    isResponse = entity.getContent();
    responseBody = convertStreamToString(isResponse);

    return responseBody;
  1. Should I do something more? Does he put the cookie on my device automatically and the HttpGet method knows to use it in order to keep the sessionID using the cookie?

  2. How can I check if the cookie exist on my device, in order to know if the session is "alive"?

  3. In case I use the following code to get the cookie:

    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(strUrl);
    HttpResponse response = mClient.execute(httpget,localContext);
    

does the HttpGet still handles the cookies the same as before?

  1. I see that DefaultHttpClient (mClient in the code above) has its own CookieStore. How can I save its cookies and load them next time I create it?
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
Asaf Pinhassi
  • 15,177
  • 12
  • 106
  • 130

3 Answers3

6

So... After cracking my head for hours and implementing my own primitive CookieStore, I found Android Asynchronous Http Client implementation, that includes a nice PersistentCookieStore that works great! Simply added the jar to my project and used it as follows:

PersistentCookieStore cookieStore = new PersistentCookieStore(context);
DefaultHttpClient mClient = new DefaultHttpClient();    
mClient.setCookieStore(cookieStore);

and that's it! The cookies are saved and reused when the application is open again.

Thank you James Smith, where ever you are. You made at least one man happy.

If anyone interested in my own primitive implementation (that also works) here it is:

package com.pinhassi.android.utilslib;

import java.util.Date;
import java.util.List;

import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class MyPersistentCookieStore extends BasicCookieStore {
private static final String COOKIES_LIST = "CookiesList";
private static final String COOKIES_NAMES = "CookiesNames";

private Context mContext;
/**
 * 
 */
public MyPersistentCookieStore(Context context) {
    super();
    mContext = context;
    load();
}

@Override
public synchronized void clear(){
    super.clear();
    save();
}

@Override
public synchronized boolean clearExpired(Date date){
    boolean res = super.clearExpired(date);
    save();
    return res;
}

@Override
public synchronized void addCookie(Cookie cookie){
    super.addCookie(cookie);
    save();
}

@Override
public synchronized void addCookies(Cookie[] cookie){
    super.addCookies(cookie);
    save();
}

public synchronized void save()
{
    Editor editor = mContext.getSharedPreferences(COOKIES_LIST, Context.MODE_PRIVATE).edit();
    editor.clear();
    List <Cookie> cookies = this.getCookies();
    StringBuilder sb = new StringBuilder();
    for (Cookie cookie : cookies)
    {
        editor.putString(cookie.getName(),cookie.getValue());
        sb.append(cookie.getName()+";");
    }
    editor.putString(COOKIES_NAMES,sb.toString());
    editor.commit();
}

public synchronized void load()
{
    SharedPreferences prefs = mContext.getSharedPreferences(COOKIES_LIST, Context.MODE_PRIVATE);
    String [] cookies = prefs.getString(COOKIES_NAMES,"").split(";");
    for (String cookieName : cookies){
        String cookieValue = prefs.getString(cookieName, null);
        if (cookieValue!=null)
            super.addCookie(new BasicClientCookie(cookieName,cookieValue));
    }

    }

}
Asaf Pinhassi
  • 15,177
  • 12
  • 106
  • 130
2

No, cookies are not handled automatically. To save cookies automatically use BasicCookeStore

More info on usage is here: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/statemgmt.html

Also see this answer: Android HttpClient persistent cookies

Community
  • 1
  • 1
Peter Knego
  • 79,991
  • 11
  • 123
  • 154
0

I haven't had to care about cookies. When I create my DefaultHttpClient and do the httpclient.execute(httpget); as here the object stores the session on it. So first I do the login and later I can use the private functions of my API. If I want to logout, I create a new instance of my object DefaultHttpClient or call the logout function.

So in case you want to use the cookie's information use the CookieStore, if not just use a singleton instance to keep alive the object DefaultHttpClient

Community
  • 1
  • 1
Dayerman
  • 3,973
  • 6
  • 38
  • 54
  • I see that DefaultHttpClient (mClient in the code above) has its own CookieStore. How can I save its cookies and load them next time I create it? – Asaf Pinhassi Sep 15 '11 at 13:00
  • Why do you need to do that? Next time you will use a new cookie. But If you still need to store it you can see the code in the example I told you how to do it. – Dayerman Sep 15 '11 at 14:07
  • I need to be able to save to cookie so I would know if the user has a session to the server even if the user quits the application and opens its again (I couldn't how to do it on the link you sent). Something similar is done in the facebook API, only they use Android browser to do it. I found a solution and published it here as an answer. Thanks a lot for your help anyway! – Asaf Pinhassi Sep 16 '11 at 09:50