【问题标题】:How to get all cookies from CookieManager android ?如何从 CookieManager android 获取所有 cookie?
【发布时间】:2016-03-04 21:35:40
【问题描述】:

对于Android CookieManager 类,有一个方法——getCookie(String url)
为此,我们需要知道正确的网址。
有没有办法在 CookieManager 中获取所有 cookie 并获取 urls 。 像getCookies 之类的东西?? 这只是为了仔细检查我是否在我的url 中为getCookie(String url) 通话提供了任何错误。 当我调用相同的时,我没有得到 cookie。
我在 url 中传递了完整的 IP address。像这样的东西:"xx.x.x.x"

谢谢
米娅

【问题讨论】:

  • 我正在尝试在成功登录后从 webview 中提取 cookie - 很简单 -- String cookieString = CookieManager.getInstance().getCookie("xx.x.x.x);

标签: android cookies


【解决方案1】:

我在我的 Android 应用程序中使用了带有 java.net 包的 CookieManager,它就像一个魅力。这是一个代码 sn-p :

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

}

【讨论】:

  • @stan 当我想使用 getCookieValue() 时,我必须创建 MyCookieManager 类的对象,并且构造函数将被调用,并且每次都会生成新的 CookieManager 瞬间而不保存 cookie。如何从我之前存储 cookie 的默认 CookieManager 中检索 cookie?
  • @HarshalBhatt,假设您在应用程序中创建并保留了一个 MyCookieManager 实例。无论如何,所有实例通常都应从默认 cookie 存储(或自定义存储,如果您更改源以在 CookieManager 构造函数中提供特定存储)返回相同的 cookie。
【解决方案2】:

您可以use reflection查看cookie映射。它在 4.0.3 中称为 mCookieMap(可能在早期版本中也是如此)。类型为地图>。

这不是一个很好的方法,因为如果不同的设备或操作系统版本不使用 mCookieMap,您将面临在不同的设备或操作系统版本上崩溃的风险,但 CookieManager 不提供了解其访问过哪些 URL 的公开方式。

【讨论】:

猜你喜欢
  • 2020-01-02
  • 1970-01-01
  • 2012-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-19
  • 1970-01-01
相关资源
最近更新 更多