snachmsm
snachmsm

Reputation: 19263

Multiple cookies in CookieManager

Lets prepare for cookie storing:

CookieSyncManager.createInstance(getApplicationContext());
CookieSyncManager.getInstance().startSync();
CookieManager.getInstance().setAcceptCookie(true);

Then I'm putting manually some cookies, lets say PHPSESSID and RANDOM

CookieManager.getInstance().setCookie("domain.com", "PHPSESSID="+phpSession);
CookieManager.getInstance().setCookie("domain.com", "RANDOM="+random);

lets check is it working using:

CookieManager.getInstance().getCookie("domain.com");

and got

PHPSESSID=dba4ff392agd39b5951d10a91a0a7b56; RANDOM=266284790:1466147978:c91d0896bac59e0b

Everything looks good, but when I navigate in may app to one of WebView Activities, which are opening same domain website also setting cookies, then when I print cookie like above it looks like this:

PHPSESSID=dba4ff392agd39b5951d10a91a0a7b56;
RANDOM=266284790:1466147978:c91d0896bac59e0b;
PHPSESSID=9ecb5156cf8fc3190fbc69fd13393243;
RANDOM=265078219%3A1463147975%3Ad0448d163e9b2123

duplicated entries... when after that I manually set again e.g. RANDOM with setCookie:

PHPSESSID=dba4ff392agd39b5951d10a91a0a7b56; 
RANDOM=111111111:2222222222:33333336bac59e0b;
PHPSESSID=9ecb5156cf8fc3190fbc69fd13393243; 
RANDOM=265078219%3A1463147975%3Ad0448d163e9b2123

values set by WebView are not overwritten, only my "manually" entered... how to force WebView to use my earlier set cookie OR overwrite already set?

Upvotes: 5

Views: 5630

Answers (2)

ryanhex53
ryanhex53

Reputation: 727

As in the MDN docs about Set-Cookie you can see many different kinds of cookie values, a cookie can be set to particular Path

cookie-name=cookie-value; Path=path-value

And in CookieManager.setCookie void setCookie (String url, String value), the android reference 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.

In my opinion, the reason that you have duplicate entries is because the cookie values were in different Path. So if you want to overwrite you should make sure host path name are the same.

Upvotes: 3

paul_hundal
paul_hundal

Reputation: 381

  private void setCookieManager(String auth_token) {
    CookieSyncManager manager = CookieSyncManager.createInstance(this);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    cookieManager.removeSessionCookie();
    cookieManager.setCookie(auth_token);

    manager.sync();
}

I think you just didn't setup your cookie manager properly. Give this a try

Upvotes: 0

Related Questions