20

I'm trying to make a URLConnection that supports cookies. According to the documentation I can use:

CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);

I couldn't get this code to work, then I saw this only works for API 9 (2.3). However, I don't get an error using CookieManager in an older emulator, CookieManager exists, but can't be constructed. Is there any way to make this work for earlier versions? I tried:

            cookieManager.setAcceptCookie(true);
            URLConnection con = u.openConnection();

            con.setRequestProperty("Cookie", cookieManager.getInstance().getCookie(url););
            con.setDoOutput(true);
            con.connect();
            String addCookie = con.getHeaderField("Set-Cookie");
            System.out.println(con.getHeaderFields().toString());
            if (addCookie!=null) {
                cookieManager.getInstance().setCookie(url, addCookie);
            }

but this doesn't work.

NoBugs
  • 9,310
  • 13
  • 80
  • 146

1 Answers1

14

I was able to enable cookies using Ian Brown's CookieManager class: http://www.hccp.org/java-net-cookie-how-to.html

I renamed it to IansCookieManager, set a class variable _CM = new IansCookieManager, now it's simple:

            URLConnection conn = u.openConnection();
            _CM.setCookies(conn);
            conn.connect();
            _CM.storeCookies(conn);
            ... 
NoBugs
  • 9,310
  • 13
  • 80
  • 146
  • 2
    That's a pretty good and basic cookie manager. I like it. I also find it strange that it took the Android Engineers that long to include the `java.net.CookieManager` class. In either case, I believe the both classes (Ian's and the java.net one) only store the cookies temporarily (i.e. they will only be kept until the application process is killed). So it's quite possible the next time the user launches the App, they will need to login again/etc? – Tony Chan Aug 02 '12 at 19:02
  • 2
    True, unless you serialized the class and saved it somewhere. Also, leaving and coming back to the app isn't enough to 'exit' the app, so cookies and browser session should be preserved. – NoBugs Aug 02 '12 at 19:12
  • Right, the user would have to do some memory intensive stuff in-between to get the system to kill the app process. Serializing the cookie managing class is a good idea. Probably best to write it to internal storage using [`openFileOutput()`](http://developer.android.com/reference/android/content/Context.html#openFileOutput%28java.lang.String,%20int%29)? Right now I use a really basic method where I save just the single session cookie that is returned to me as a `String` in `SharedPreferences`. I think I'm gonna try using this serializable cookie manager now though. – Tony Chan Aug 02 '12 at 21:36