简体   繁体   English

Android中是否存在用于将Cookie格式化为CookieManager值的类?

[英]Is there a class in Android for formatting Cookies into the value for a CookieManager?

When my app starts up, I post a login request to a web service and receive a Cookie. 当我的应用程序启动时,我将登录请求发布到Web服务并收到Cookie。 I want to use that Cookie in my WebView, which I do with the following code: 我想在我的WebView中使用该Cookie,可通过以下代码进行操作:

List<Cookie> cookies = this.get_my_cookies_from_somewhere();
CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();

for (Cookie cookie : cookies) {
    String rawUrl = (cookie.isSecure() ? "https" : "http") + "://" + cookie.getDomain() + cookie.getPath();
    cookieManager.setCookie(rawUrl, cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain());
}
cookieSyncManager.sync();

Ideally, I would like to have the cookie url and "Set-Cookie" header value required by the CookieManager be built by the Cookie class or some utility class. 理想情况下,我想由Cookie类或某些实用程序类来构建CookieManager所需的cookie url和“ Set-Cookie”标头值。 Does such a thing exist? 这样的事情存在吗?

I tried RFC2109Spec and RFC2965Spec, but they produce the "Cookie" header, not the "Set-Cookie" header. 我尝试了RFC2109Spec和RFC2965Spec,但它们产生的是“ Cookie”标头,而不是“ Set-Cookie”标头。

The preferred method appears to be to send the Headers from your Response directly to the CookieManager. 首选方法似乎是将标题从您的响应直接发送到CookieManager。 I'm basing this on code I found from Romain Guy : 我将此基于我从Romain Guy找到的代码

final CookieManager cookieManager = CookieManager.getInstance();
final HttpResponse response = ...
final Header[] cookies = response.getHeaders("set-cookie");
for (Header cooky : cookies) {
    cookieManager.setCookie(url, cooky.getValue());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM