Android cookies正确的更新方式

之前的更新方式

一搜cookies的使用,非常easy搜到非常多文章。主要的几步大致同样。例如以下图:

这里写图片描写叙述

基本上都要求大家先调用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 {@link #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一下。这样就完美了。

希望能帮到你。

原文地址:https://www.cnblogs.com/jzssuanfa/p/7237743.html