之前的更新方式
一搜cookies的使用,很容易搜到很多文章,基本的几步大致相同,如下图:
基本上都要求大家先调用cookieManager.removeAllCookie()或者调用 cookieManager.removeSessionCookie(),这样确实每一次的setCookie都能写入新的cookie,简单粗暴有效。
遇到的问题
大家看setCookies的方法:
/** * 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. * * @param url the URL for which the cookie is to be set * @param value the cookie as a string, using the format of the 'Set-Cookie' * HTTP response header */ public void setCookie(String url, String value) { throw new MustOverrideException(); }
每一个cookies是对应一个url的
再看removeSessionCookie
/** * Removes all session cookies, which are cookies without an expiration * date. * @deprecated use [email protected] #removeSessionCookies(ValueCallback)} instead. */ public void removeSessionCookie() { throw new MustOverrideException(); }
这可不是只清掉了你所使用的那个url,而是清掉了所有的cookie,这就不对了,你怎么能随意清除掉所有的cookie呢,说不定其他的同事针对另外一个url写入了相对应的cookie,说不定h5的同学也在cookie中写入了很多有用的东西,你调用cookieManager.removeSessionCookie()后就是把所有的cookie清空了。
cookieManager.removeAllCookie()也是一样的道理
解决办法
请仔细看setCookie在Api中的方法注解:
* 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.
很明显,你如果只想更新你自己使用的url的cookie的话,不用删除cookies,只要再次setCookie,系统会自动检查之前这个url有没有cookie,如果有,就替换掉,如果没有,就直接写入。
注意
CookieSyncManager跟CookieManager.removeAllCookie()、CookieManager.removeSessionCookie()都已经废弃,在api21以上的sok中同步cookie提供了 cookieManager.flush(),所以正确的setCookie应该如下:
String url = null; url = "http://higo.xxx.xxx"; CookieManager cookieManager = CookieManager.getInstance(); cookieManager.setAcceptCookie(true); String cookies = "cookie"; cookieManager.setCookie(url, "xxx=" +cookies); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { cookieManager.flush(); } else { CookieSyncManager.createInstance(this.getApplicationContext()); CookieSyncManager.getInstance().sync(); }
cookie中分号的使用
cookie中默认就是以分号分割的
比如你写入这样的cookie
String cookie = "name=cookie;year=2015";setCookie("http://xxx.xxx",cookie);
那其实只把name=cookie写入到了http://xxx.xxx这个域名下,为什么year=2015没有写入呢,因为分号“;”是cookie默认的分割符,cookie认为出现“;”当前的cookie的值就结束了。
那能不能不使用“;”去;连接字符串呢?
最好不要这样做,因为大家都认为cookie的分隔符就是“;”,如果你换成了另外一种,当有的同事不知道的话,就出问题了。
正确的方式应该是怎么样的呢?
使用base64转码一下就可以了,这样做你还能把信息加密一次,当然需要你跟h5的同学沟通一下,他那边拿到cookie的值需要base64一下,这样就完美了。
希望能帮到你。
版权声明:本文为博主原创文章,未经博主允许不得转载。