如何使用CookieManager删除特定域的cookie?

时间:2010-05-14 12:43:55

标签: android cookies webkit

我知道CookieManager的存在,但如何仅删除域名的Cookie?

有人可以帮我处理一些代码片段吗?

4 个答案:

答案 0 :(得分:11)

public void clearCookies(String domain) {
    CookieSyncManager.createInstance(this);
    CookieManager cookieManager = CookieManager.getInstance();
    String cookiestring = cookieManager.getCookie(domain);
    String[] cookies =  cookiestring.split(";");
    for (int i=0; i<cookies.length; i++) {
        String[] cookieparts = cookies[i].split("=");
        cookieManager.setCookie(domain, cookieparts[0].trim()+"=; Expires=Wed, 31 Dec 2025 23:59:59 GMT");
    }
    CookieSyncManager.getInstance().sync();
}

答案 1 :(得分:9)

调用android.webkit.CookieManager的{​​{1}}方法为您感兴趣的网址或域生成RFC 2109 getCookie标头。解析cookie标头以获取cookie名称列表。对于每个cookie名称,为该名称生成一个RFC 2109 Cookie标头,该标头具有过去的过期日期,并将其传递给Set-Cookie的{​​{1}}方法。虽然API文档指定CookieManager忽略已过期的值,但Android的当前实现实际上会刷新cookie。为了防止未来实现忽略文档中指定的过期值,请检查cookie是否实际被删除并执行一些后备行为(如果他们没有 - setCookie的{​​{1}}方法可能有用对于这个后备。

答案 2 :(得分:3)

以下是来自开源项目的代码示例。也许可以帮助别人。

https://github.com/janrain/engage.android/blob/96f21b45738ef82a911e27d8a707aff3a1024d36/Jump/src/com/janrain/android/utils/WebViewUtils.java

private static void deleteWebViewCookiesForDomain(Context context, String domain, boolean secure) {
    CookieSyncManager csm = CookieSyncManager.createInstance(context);
    CookieManager cm = CookieManager.getInstance();

    /* http://code.google.com/p/android/issues/detail?id=19294 */
    if (AndroidUtils.SDK_INT >= 11) {
        // don't trim leading '.'s
    } else {
        /* Trim leading '.'s */
        if (domain.startsWith(".")) domain = domain.substring(1);
    }

    /* Cookies are stored by domain, and are not different for different schemes (i.e. http vs
     * https) (although they do have an optional 'secure' flag.) */
    domain = "http" + (secure ? "s" : "") + "://" + domain;
    String cookieGlob = cm.getCookie(domain);
    if (cookieGlob != null) {
        String[] cookies = cookieGlob.split(";");
        for (String cookieTuple : cookies) {
            String[] cookieParts = cookieTuple.split("=");

            /* setCookie has changed a lot between different versions of Android with respect to
             * how it handles cookies like these, which are set in order to clear an existing
             * cookie.  This way of invoking it seems to work on all versions. */
            cm.setCookie(domain, cookieParts[0] + "=;");

            /* These calls have worked for some subset of the the set of all versions of
             * Android:
             * cm.setCookie(domain, cookieParts[0] + "=");
             * cm.setCookie(domain, cookieParts[0]); */
        }
        csm.sync();
    }
}

答案 3 :(得分:1)

我还没有看到在API中这样做,但你总是可以深入了解真正的源代码(开源很好)...例如,我在这个类中找到了这个deleteCookies方法:WebViewDatabase,它是Android核心的一部分。

正如你所看到的那样...... cookies只是SQLite数据库中的行...所以如果你能让这个课程成功,至少你知道如何自己做。