How to remove cookies using CookieManager for a specific domain?

前端 未结 4 1080
半阙折子戏
半阙折子戏 2020-12-14 13:08

I know about the existince of CookieManager, but how do I remove cookies of a domain only?

Can someone help me with some code fragment?

4条回答
  •  时光说笑
    2020-12-14 13:49

    Here is a code sample from an open source project. Maybe could help someone.

    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();
        }
    }
    

提交回复
热议问题