標籤:
首先android5.0 實現了WebView與 架構的自動cookie同步,無需額外操作。
5.0一下版本需要手動同步cookie
方法如下
<pre name="code" class="java">CookieSyncManager.createInstance(context); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.setAcceptCookie(true); cookieManager.removeAllCookie(); List<Cookie> cookies = new PersistentCookieStore(context).getCookies(); for (Cookie cookie : cookies) { //注意這裡為什麼放肆的寫了個cookie.getDomain(),而不是像api裡邊說的url,類似baidu.com如果是網域名稱,直接設定“baidu.com“, cookieManager.setCookie(<span style="color:#ff0000;">cookie.getDomain()</span>, cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain() + "; path=" + cookie.getPath()); } CookieSyncManager.getInstance().sync();
這涉及到了cookie的知識,設定cookie時,會先檢測cookie的Domain是否和url網址的網域名稱一致,如果不一致設定cookie失敗。
所以url在裡邊起到作用,就是檢測Domain網域名稱, 設定在這個網域名稱下的所有url的請求的cookie。
如果是設定一個設定二級的url,反倒不容易理解。
看看google 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 * must not have expired and must not be a session cookie, otherwise it * will be ignored. * * @param url the URL for which the cookie is 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(); } url the URL for which the cookie is set ,如果不瞭解cookie的原理,這讓解釋更容易讓讀者理解為,只是設定了這個子url的cookie
android WebView 和 HttpClient cookie同步