转载地址:http://blog.csdn.net/coder_nice/article/details/47780947
之前的更新方式
一搜cookies的使用,很容易搜到很多文章,基本的几步大致相同,如下图:
基本上都要求大家先调用cookieManager.removeAllCookie()或者调用 cookieManager.removeSessionCookie(),这样确实每一次的setCookie都能写入新的cookie,简单粗暴有效。
遇到的问题
大家看setCookies的方法:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
每一个cookies是对应一个url的
再看removeSessionCookie
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
这可不是只清掉了你所使用的那个url,而是清掉了所有的cookie,这就不对了,你怎么能随意清除掉所有的cookie呢,说不定其他的同事针对另外一个url写入了相对应的cookie,说不定h5的同学也在cookie中写入了很多有用的东西,你调用cookieManager.removeSessionCookie()后就是把所有的cookie清空了。
cookieManager.removeAllCookie()也是一样的道理解决办法
请仔细看setCookie在Api中的方法注解:
- 1
- 2
- 3
- 4
- 1
- 2
- 3
- 4
很明显,你如果只想更新你自己使用的url的cookie的话,不用删除cookies,只要再次setCookie,系统会自动检查之前这个url有没有cookie,如果有,就替换掉,如果没有,就直接写入。
注意
CookieSyncManager跟CookieManager.removeAllCookie()、CookieManager.removeSessionCookie()都已经废弃,在api21以上的sok中同步cookie提供了 cookieManager.flush(),所以正确的setCookie应该如下:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
cookie中分号的使用
cookie中默认就是以分号分割的
比如你写入这样的cookie
- 1
- 2
- 3
- 1
- 2
- 3
那其实只把name=cookie写入到了http://xxx.xxx这个域名下,为什么year=2015没有写入呢,因为分号“;”是cookie默认的分割符,cookie认为出现“;”当前的cookie的值就结束了。
那能不能不使用“;”去;连接字符串呢?
最好不要这样做,因为大家都认为cookie的分隔符就是“;”,如果你换成了另外一种,当有的同事不知道的话,就出问题了。
正确的方式应该是怎么样的呢?
使用base64转码一下就可以了,这样做你还能把信息加密一次,当然需要你跟h5的同学沟通一下,他那边拿到cookie的值需要base64一下,这样就完美了。
希望能帮到你。
webview设置cookies的正确方式
最新推荐文章于 2024-07-31 21:39:24 发布