我想提出一种完全不同的方法来解决你的问题。不要通过复制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<String, List<String>> responseHeaders) throws IOException
{
if ((uri == null) || (responseHeaders == null)) return;
String url = uri.toString();
for (String headerKey : responseHeaders.keySet())
{
if ((headerKey == null) || !(headerKey.equalsIgnoreCase("Set-Cookie2") || headerKey.equalsIgnoreCase("Set-Cookie"))) continue;
for (String headerValue : responseHeaders.get(headerKey))
{
this.webkitCookieManager.setCookie(url, headerValue);
}
}
}
@Override
public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException
{
if ((uri == null) || (requestHeaders == null)) throw new IllegalArgumentException("Argument is null");
String url = uri.toString();
Map<String, List<String>> res = new java.util.HashMap<String, List<String>>();
String cookie = this.webkitCookieManager.getCookie(url);
if (cookie != null) res.put("Cookie", Arrays.asList(cookie));
return res;
}
@Override
public CookieStore getCookieStore()
{
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);