做一个webview组件,思路如下:
用户首次登陆,cookie为空,webivew.load(url),然后通过onPageLoaded获得cookie,再setCookie,下次用户二次登陆可以直接登陆而不用输入账号密码。
代码如下:
url1 = "https://www.chiphell.com/";
webView = (WebView) findComponentById(ResourceTable.Id_webview);
webView.getWebConfig().setJavaScriptPermit(true);
cookieStore = CookieStore.getInstance();
cookieStore.setCookieEnable(true);
cookieStore.setCrossDomainCookieEnable(webView, true);
if (cookieStore.getCookie(url1) == null) {/%ra2
webView.load(url1);
} else {
String[] cookies = cookieStore.getCookie(url1).split(";");
for (int i = 0; i < cookies.length; i++) {
cookieStore.setCookie(url1,cookies[i]);
}
cookieStore.persist();
webView.load(url1);
}
webView.setWebAgent(new WebAgent() {
@Override
public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
return true;
}
@Override
public void onPageLoaded(WebView webView, String url) {
super.onPageLoaded(webView, url);
cookieStore.setCookieEnable(true);
cookieStore.setCrossDomainCookieEnable(webView, true);
cookieStore.getCookie(url1);
cookieStore.persist();
}
});
在setCookie中能看到key=value值,但是app进程一结束,cookie就失效。此问题困扰我好几天,望各位不吝赐教!谢谢!