How to get all cookies from CookieManager android ?

后端 未结 2 1291
你的背包
你的背包 2021-02-13 00:25

For Android CookieManager class there is a method -- getCookie(String url).
For this we need to know correct url.
Is there a way to get all co

相关标签:
2条回答
  • 2021-02-13 00:45

    I used the CookieManager with the java.net package in my Android Application and it works like a charm. Here is a code snippet :

    import java.net.CookieHandler;
    import java.net.CookieManager;
    import java.net.CookiePolicy;
    import java.net.HttpCookie;
    import java.util.List;
    
    private class MyCookieManager
    {       
        private CookieManager mCookieManager = null;
    
        MyCookieManager() {
            mCookieManager = new CookieManager();
            mCookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
            CookieHandler.setDefault(mCookieManager);
        }
    
        private List<HttpCookie> getCookies() {
            if(mCookieManager == null)
                return null;
            else
                return mCookieManager.getCookieStore().getCookies();
        }
    
        public void clearCookies() {
            if(mCookieManager != null)
                mCookieManager.getCookieStore().removeAll();
        } 
    
        public boolean isCookieManagerEmpty() {
            if(mCookieManager == null)
                return true;
            else 
                return mCookieManager.getCookieStore().getCookies().isEmpty();
        }
    
    
        public String getCookieValue() {
            String cookieValue = new String();
    
            if(!isCookieManagerEmpty()) {
                for (HttpCookie eachCookie : getCookies())
                    cookieValue = cookieValue + String.format("%s=%s; ", eachCookie.getName(), eachCookie.getValue());
            }
    
            return cookieValue;
        }
    
    }
    
    0 讨论(0)
  • 2021-02-13 00:53

    You can use reflection to see the cookie map. It's called mCookieMap in 4.0.3 (and probably in earlier releases as well). The type is Map>.

    This isn't a great way of doing it because you'll risk breaking on different devices or OS versions if they don't use mCookieMap, but CookieManager doesn't offer a public way of knowing which URLs it's visited.

    0 讨论(0)
提交回复
热议问题