android WebView 和 HttpClient cookie同步

來源:互聯網
上載者:User

標籤:

首先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同步

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.