java 同步cookie,双向同步的HttpURLConnection(java.net.CookieManager)和WebView(android.webkit.CookieManager)...

越飞翮
2023-12-01

我实现了自己的想法。它实际上很酷。我创建了自己的java.net.CookieManager实现,它将所有请求转发到WebViews的webkit android.webkit.CookieManager。这意味着不需要同步,HttpURLConnection使用与WebView相同的cookie存储。

类WebkitCookieManagerProxy:

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

}

public 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);

测试

我的初始测试表明这是工作很好。我看到在WebViews和HttpURLConnection之间共享的Cookie。我希望我不会遇到任何问题。如果你尝试这个,发现任何问题,请评论。

 类似资料: