java cookiesmanager,将Cookie从HttpURLConnection(java.net.CookieManager)传递到WebView(android.webkit.Cooki...

我想建议一个完全不同的方法来解决你的问题。不是将Cookie从一个地方复制到另一个地方(手动同步),让我们让HttpURLConnection和WebViews使用相同的cookie存储。

这完全消除了对同步的需要。在其中任何一个更新的任何cookie,将立即并自动反映在其他。

为此,创建自己的java.net.CookieManager实现,它将所有请求转发到WebViews的webkit android.webkit.CookieManager。

实施:

import java.io.IOException;

import java.net.CookieManager;

import java.net.CookiePolicy;

import java.net.CookieStore;

import java.net.URI;

import java.util.Arrays;

import java.util.List;

import java.util.Map;

public class WebkitCookieManagerProxy extends CookieManager

{

private android.webkit.CookieManager webkitCookieManager;

public WebkitCookieManagerProxy()

{

this(null, null);

}

WebkitCookieManagerProxy(CookieStore store, CookiePolicy cookiePolicy)

{

super(null, cookiePolicy);

this.webkitCookieManager = android.webkit.CookieManager.getInstance();

}

@Override

public void put(URI uri, Map> responseHeaders) throws IOException

{

// make sure our args are valid

if ((uri == null) || (responseHeaders == null)) return;

// save our url once

String url = uri.toString();

// go over the headers

for (String headerKey : responseHeaders.keySet())

{

// ignore headers which aren't cookie related

if ((headerKey == null) || !(headerKey.equalsIgnoreCase("Set-Cookie2") || headerKey.equalsIgnoreCase("Set-Cookie"))) continue;

// process each of the headers

for (String headerValue : responseHeaders.get(headerKey))

{

this.webkitCookieManager.setCookie(url, headerValue);

}

}

}

@Override

public Map> get(URI uri, Map> requestHeaders) throws IOException

{

// make sure our args are valid

if ((uri == null) || (requestHeaders == null)) throw new IllegalArgumentException("Argument is null");

// save our url once

String url = uri.toString();

// prepare our response

Map> res = new java.util.HashMap>();

// get the cookie

String cookie = this.webkitCookieManager.getCookie(url);

// return it

if (cookie != null) res.put("Cookie", Arrays.asList(cookie));

return res;

}

@Override

public CookieStore getCookieStore()

{

// we don't want anyone to work with this cookie store directly

throw new UnsupportedOperationException();

}

}

并最终通过在应用程序初始化时使用它:

android.webkit.CookieSyncManager.createInstance(appContext);

// unrelated, just make sure cookies are generally allowed

android.webkit.CookieManager.getInstance().setAcceptCookie(true);

// magic starts here

WebkitCookieManagerProxy coreCookieManager = new WebkitCookieManagerProxy(null, java.net.CookiePolicy.ACCEPT_ALL);

java.net.CookieHandler.setDefault(coreCookieManager);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值