android webview 保存 cookie,Android WebView js混合cookie和localStorage存储

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

标签:Constant,String,cookieManager,UICPS,token,cookie,localStorage,Android

来源: https://www.cnblogs.com/huihuizhang/p/11766519.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值