CookieManager#setCookie
CookieManager#setCookie is a method for synchronizing cookies between native Android apps and web views. If you are using a 3rd-party account SDK, and can get cookies from them, you can synchronize these to make a seamless experience.
But some behaviors of CookieManager#setCookie are not described in the document.
The document of CookieManager#setCookie says:
Sets a cookie for the given URL. Any existing cookie with the same host, path and name will be replaced with the new cookie. The cookie being set will be ignored if it is expired.
Watch Out!
But that is not true, there is a trap in it. If a cookie contains multiple key-value pairs which are separated by semicolons, for example:
k1=v1; k2=v2; k3=v3;
Then, you may set cookies by using:
CookieManager cookieMgr = CookieManager.getInstance();
cookieMgr.setCookie("http://host.name/", "k1=v1; k2=v2; k3=v3;");
// What's the result?
String result = cookieMgr.getCookie("http://host.name/");
Here is the trap. The result of cookieManager.getCookie(…) is NOT “k1=v1; k2=v2; k3=v3;”, but “k1=v1”. The other pairs are missing.
So … how?
So, how can it work as expected? Let’s try another way. If we set cookie pair one by one using this way:
CookieManager cookieMgr = CookieManager.getInstance();
cookieMgr.setCookie(“http://host.name/", “k1=v1;”);
cookieMgr.setCookie(“http://host.name/", “k2=v2;”);
cookieMgr.setCookie(“http://host.name/", “k3=v3;”);
// What’s the result?
String result = cookieMgr.getCookie(“http://host.name/“);
After that, the returned value will be “k1=v1; k2=v2; k3=v3;”, which is what we expected.
Split it
You may have noticed that the original cookie string should be split by semicolons. We can use method String#split to split it.
The result would look like this:
String cookie = “k1=v1; k2=v2; k3=v3;”;
String[] array = cookie.split(“;”);
CookieManager cookieMgr = CookieManager.getInstance();
for (String c : array) {
cookieMgr.setCookie(“http://host.name/", c);
}