Month: January 2014

Android – Adding Custom cookies to a WebView

This is just a quick post about adding cookies to a web view. If you’ve ever tried to do this the way most people have said that it should be done, you’ve failed miserably and found this post. 🙂

The way it’s supposed to work is you set the cookie on the CookieManager and then tell the CookieSyncManager to sync.

1
2
CookieManager.getInstance().setCookie(domain, value);
CookieSyncManager.getInstance().sync();

I’ve never got this to work as described. With or without async tasks waiting for the threads to catch up.

Instead, I just add the cookie in the header of all the loadUrl calls.

1
2
3
Map<String, String> headers = new HashMap<String, String>();
headers.put("Cookie", "cookieName=cookieValue;domain=domain.com;path=/;Expires=Thu, 2 Aug 2021 20:47:11 UTC;");
webView.loadUrl("myurl.com", headers );

Caveat: I only need to initially load the appropriate cookie for the request, if you want to cover nested calls from inside the browser, you need to override shouldOverrideUrlLoading.

1
2
3
4
5
6
7
webView.setWebViewClient(new WebViewClient() {
     @Override
     public boolean shouldOverrideUrlLoading(WebView view, String url) {
         view.loadUrl(url, headers);
         return false;
     }
});

If you need to inject the cookie for all requests(including images, js, etc), you’re going to need to override shouldInterceptRequest, which I didn’t have to do so no example, sorry. Good luck!! 🙂