一、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
