一、cookie存储和取出:
(1)存储:
-------------------
**在loadURL之前调用**
--------------------
/**
* 同步一下cookie
*/
public void synCookies(String url) {
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.acceptCookie();
cookieManager.removeSessionCookie();// 移除
cookieManager.removeAllCookie();
/**
* cookies是在HttpClient中获得的cookie
*/
String token = (String) SpUtils.getParam(getApplicationContext(), Constant.TOKEN, "'");
String phone = (String) SpUtils.getParam(getApplicationContext(), Constant.PHONENUMBER, "'");
if (TextUtils.isEmpty(token)) {
return;
}
cookieManager.setCookie(url, Constant.UICPS_USERID + "=" + token);
cookieManager.setCookie(url, Constant.UICPS_USERPHONE + "=" + phone);
/**
* 判断系统当前版本,同步方式不一样
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cookieManager.flush();
} else {
CookieSyncManager.createInstance(getApplicationContext()).sync();
}
}
(2)取出:
url:web地址
if (CookieManager.getInstance().hasCookies()) {//如果存在token就获取 String cookies = CookieManager.getInstance().getCookie(url); }
二、LocalStorage存储和取出: 设置LocalStorage 在onPageFinished中调用
(1)存储
第一步:设置
//存储设置
webSettings.setDomStorageEnabled(true); webSettings.setAppCacheMaxSize(1024 * 1024 * 8); String appCachePath = getContext().getCacheDir().getAbsolutePath(); webSettings.setAppCachePath(appCachePath);
第二步:存储
/**
* 网页加载完毕
*/
@Override protected void onPageFinished(WebView view, String url) { writeLocalStorage(); } /** * 写入LocalStorage */ private void writeLocalStorage() { String token = (String) SpUtils.getParam(getApplicationContext(), Constant.TOKEN, ""); String phone = (String) SpUtils.getParam(getApplicationContext(), Constant.PHONENUMBER, ""); if (TextUtils.isEmpty(token)) { return; } if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { if (contentWebView != null) { contentWebView.evaluateJavascript("window.localStorage.setItem('" + Constant.UICPS_USERID + "','" + token + "');", null); contentWebView.evaluateJavascript("window.localStorage.setItem('" + Constant.UICPS_USERPHONE + "','" + phone + "');", null); } } else { if (contentWebView != null) { contentWebView.loadUrl("javascript:localStorage.setItem('" + Constant.UICPS_USERID + "','" + token + "');"); contentWebView.loadUrl("javascript:localStorage.setItem('" + Constant.UICPS_USERPHONE + "','" + phone + "');"); } } }
(2)取出
在前端取出
//token为存入的key值
localStorage.getItem("token")
web 参考API:
https://blog.csdn.net/CodingEnding/article/details/78898210
