Android小记-根据domain清除cookie

Posted everlastxgb

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android小记-根据domain清除cookie相关的知识,希望对你有一定的参考价值。

android WebView中可以直接全部清除cookie,但如果我们想要根据某个域名指定清除cookie,则大概代码如下:

必要方法:


    public static void clearCookieByUrl(String url, CookieManager pCookieManager, CookieSyncManager pCookieSyncManager) 
        Uri uri = Uri.parse(url);
        String host = uri.getHost();
        clearCookieByUrlInternal(url, pCookieManager, pCookieSyncManager);
        clearCookieByUrlInternal("http://." + host, pCookieManager, pCookieSyncManager);
        clearCookieByUrlInternal("https://." + host, pCookieManager, pCookieSyncManager);
    

    private static void clearCookieByUrlInternal(String url, CookieManager pCookieManager, CookieSyncManager pCookieSyncManager) 
        if (TextUtils.isEmpty(url)) 
            return;
        
        String cookieString = pCookieManager.getCookie(url);
        Vector<String> cookie = getCookieNamesByUrl(cookieString);
        if (cookie == null || cookie.isEmpty()) 
            return;
        
        int len = cookie.size();
        for (int i = 0; i < len; i++) 
            pCookieManager.setCookie(url, cookie.get(i) + "=-1");
        
        pCookieSyncManager.sync();
    

    private static Vector<String> getCookieNamesByUrl(String cookie) 
        if (TextUtils.isEmpty(cookie)) 
            return null;
        
        String[] cookieField = cookie.split(";");
        int len = cookieField.length;
        for (int i = 0; i < len; i++) 
            cookieField[i] = cookieField[i].trim();
        
        Vector<String> allCookieField = new Vector<String>();
        for (int i = 0; i < len; i++) 
            if (TextUtils.isEmpty(cookieField[i])) 
                continue;
            
            if (!cookieField[i].contains("=")) 
                continue;
            
            String[] singleCookieField = cookieField[i].split("=");
            allCookieField.add(singleCookieField[0]);
        
        if (allCookieField.isEmpty()) 
            return null;
        
        return allCookieField;
    

调用方式:

        String domainUrl = "http://www.facebook.com";
        CookieManager mCookieManager = CookieManager.getInstance();
        CookieSyncManager mCookieSyncManager = CookieSyncManager.createInstance(getApplicationContext());
        Utils.clearCookieByUrl(domainUrl , mCookieManager, mCookieSyncManager);

以上是关于Android小记-根据domain清除cookie的主要内容,如果未能解决你的问题,请参考以下文章

Django学习小记-cookie

没有前导点的 Javascript cookie

使用 SAML 单次注销 (SLO) 调用注销 URL 后如何清除 Android 网络视图 cookie?

Cookie格式

java 根据访问的地址 获得cookie

网络请求的Cookie组成