试试这个方法
public List<Cookie> sync(String url) {
CookieManager cookieManager = CookieManager.getInstance();
if (cookieManager == null)
return null;
RFC2109Spec cookieSpec = new RFC2109Spec();
String rawCookieHeader = null;
try {
URL parsedURL = new URL(url);
rawCookieHeader = cookieManager.getCookie(parsedURL.getHost());
if (rawCookieHeader == null)
return null;
int port = parsedURL.getPort() == -1 ? parsedURL.getDefaultPort() : parsedURL.getPort();
CookieOrigin cookieOrigin = new CookieOrigin(parsedURL.getHost(), port, "/", false);
List<Cookie> cookies = cookieSpec.parse(new BasicHeader("set-cookie", rawCookieHeader), cookieOrigin);
return cookies;
} catch (Exception e) {
}
return null;
}
public void sync(List<Cookie> cookies,String url) {
if (cookies != null) {
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
for (Cookie cookie : cookies) {
Cookie sessionInfo = cookie;
String cookieString = sessionInfo.getName() + "=" + sessionInfo.getValue() + "; domain=" + sessionInfo.getDomain();
cookieManager.setCookie(url, cookieString);
CookieSyncManager.getInstance().sync();
}
}
}
如何使用
webview.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
sync(url); // store list of cookies in Global variable return by this function.
}
});
//before loading/swithich account
//sync(yourglobalvariable of list of cookis, url of respective account);
sync(cookies,urlAccount1);
webview.loadUrl(url);