標籤:cookie android
之前的更新方式
一搜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 {@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一下,這樣就完美了。
希望能幫到你。
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Android cookies正確的更新方式