1.WebView初始化的时候用倒如下代码:
if (Build.VERSION.SDK_INT >= 21) {
CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView, true);
}
syncCookie(this, url);
2.实现Cookie储存方法
/**
* Sync Cookie
*/
private void syncCookie(Context context, String url) {
try {
CookieSyncManager.createInstance(context);
cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();// 移除
cookieManager.removeAllCookie();
String oldCookie = cookieManager.getCookie(url);
if (oldCookie != null) {
Log.d("oldCookie", oldCookie);
}
StringBuilder sbCookie = new StringBuilder();
String userId = BKSetting.getUserId(this);
sbCookie.append(String.format("user_id=%s", userId));//我自己放的Cookie
String cookieValue = sbCookie.toString();
cookieManager.setCookie(url, cookieValue);
CookieSyncManager.getInstance().sync();
} catch (Exception e) {
Log.e("syncCookie failed", e.toString());
}
}