Archive for the ‘Mobile’ Category

Cookies in Hybrid Android Apps

01/17/2013 9 comments

Sharing Cookies between WebViews and native code

Hybrid mobile applications require a close collaboration between native code and WebViews. Unlike iOS, Android doesn’t provide any implicit bridge between HTTP cookies in WebViews and native HTTP requests made through HttpConnection or Apache’s HttpClient interfaces. As a developer, it’s up to you to manually synchronize these systems if you want to share state or authentication context between them.

This is often a useful feature for integrating third party web services via their login page in your app’s WebView. Authentication credentials stored as HTTP cookies should be shared for subsequent HTTP calls, whether they’re native or a WebView.

Android Cookie Management and Persistence

Add CookieManager and CookieSyncManager hooks to properly setup your application to accept and save cookies, while writing them to disk periodically or when the application pauses or shuts down.


public class YourApplication extends Application {
  public void onCreate() {

    //Setup Cookie Manager and Persistence to disk

Main Activity

public class MainActivity extends BaseActivity {
  public void onResume() {

   public void onPause() {

Synchronizing Android CookieManager to Apache HttpClient

Now that cookies have an application wide cookie store that will save WebView cookies and persist the cookie store to disk, we need to sync cookies from this store for use by native code.

Synchronize native HttpClient with App’s Cookie Store
This example shows populating an Apache CookieStore configured in an HttpClient that is pre-populated with any HTTP Cookies that apply to this URL. Then, after executing the request, writing all of the cookies saves in the CookieStore into the App’s Android CookieManager.

public static String getURLContentsAsString(String url) {

  DefaultHttpClient httpClient =  new DefaultHttpClient();

  //Injects App's CookieManager cookies for this URL into HttpClient CookieStore
  syncCookiesFromAppCookieManager(url, httpClient);

  HttpGet hp = new HttpGet(url);
  HttpResponse response = hc.execute(hp);

  //Save's cookies from HttpClient in App's CookieStore
  syncCookiesToAppCookieManager(url, httpClient);

  // Process Response here

This helper function fetches all cookies for this URL from the Android CookieManager, which gives us a raw Cookie HTTP header value. The Apache CookieStore expects Cookie objects, which we will generate using the RFC2109Spec that matches the format of the Android CookieManager.

public static void syncCookiesFromAppCookieManager(String url, DefaultHttpClient httpClient) {

  BasicCookieStore cookieStore = new BasicCookieStore();

  CookieManager cookieManager = CookieManager.getInstance();
  if (cookieManager == null) return;

  RFC2109Spec cookieSpec = new RFC2109Spec();
  String rawCookieHeader = null;
  try {
    URL parsedURL = new URL(url);

    //Extract Set-Cookie header value from Android app CookieManager for this URL
    rawCookieHeader = cookieManager.getCookie(parsedURL.getHost());
    if (rawCookieHeader == null) return;

    //Convert Set-Cookie header value into Cookies w/in HttpClient CookieManager
    int port = parsedURL.getPort() == -1 ?
      parsedURL.getDefaultPort() : parsedURL.getPort();

    CookieOrigin cookieOrigin = new CookieOrigin( parsedURL.getHost(),
    List<Cookie> appCookies = cookieSpec.parse(
      new BasicHeader("set-cookie", rawCookieHeader),

    cookieStore.addCookies(appCookies.toArray(new Cookie[appCookies.size()]));
  } catch (MalformedURLException e) {
    // Handle Error
  } catch (MalformedCookieException e) {
    // Handle Error

This helper extracts Cookie objects from the Apache CookieStore and converts them into Set-Cookie header strings for the Android CookieManager.

public static void syncCookiesToAppCookieManager(String url, DefaultHttpClient httpClient) {

  CookieStore clientCookieStore = httpClient.getCookieStore();
  List<Cookie> cookies  = clientCookieStore.getCookies();
  if (cookies.size() < 1) return;

  CookieSyncManager syncManager = CookieSyncManager.getInstance();
  CookieManager appCookieManager = CookieManager.getInstance();
  if (appCookieManager == null) return;

  //Extract any stored cookies for HttpClient CookieStore
  // Store this cookie header in Android app CookieManager
  for (Cookie cookie:cookies) {
    //HACK: Work around weird version-only cookies from cookie formatter.
    if (cookie.getName() == "$Version") break;

    String setCookieHeader = cookie.getName()+"="+cookie.getValue()+
      "; Domain="+cookie.getDomain();
    appCookieManager.setCookie(url, setCookieHeader);

  //Sync CookieManager to disk if we added any cookies