Set a cookie to a webView in Android

You may want to take a look of how I am setting the a webview cookie at :

Android WebView Cookie Problem

Where in my answer you could see how I'm handling this like:

val cookieManager = CookieManager.getInstance()
cookieManager.acceptCookie()
cookieManager.setCookie(domain,"$cookieKey=$cookieValue")
cookieManager.setAcceptThirdPartyCookies(view.webViewTest,true)

Couple of comments which I found out from my experience and gave me headaches:

  1. http and https urls are different. Setting a cookie for http://www.example.com is different than setting a cookie for https://www.example.com
  2. A slash in the end of the url can also make a difference. In my case https://www.example.com/ works but https://www.example.com does not work.
  3. CookieManager.getInstance().setCookie is performing an asynchronous operation. So, if you load a url right away after you set it, it is not guaranteed that the cookies will have already been written. To prevent unexpected and unstable behaviours, use the CookieManager#setCookie(String url, String value, ValueCallback callback) (link) and start loading the url after the callback will be called.

I hope my two cents save some time from some people so you won't have to face the same problems like I did.


It's quite simple really.

String cookieString = "cookie_name=cookie_value; path=/";
CookieManager.getInstance().setCookie(baseUrl, cookieString);

where cookieString is formatted the same as a more traditional Set-Cookie HTTP header, and baseUrl is the site the cookie should belong to.