在做项目中,不免会有部分项目是要管理cookie,
1、登录成功后,把cookie保存起来,我项目中就把cookie保存到Application里:
获取cookie
/**
* 获取标准 Cookie
*/
private String getCookieText() {
PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
List<Cookie> cookies = myCookieStore.getCookies();
for (Cookie cookie : cookies) {
}
Cookie cookie = null;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < cookies.size(); i++) {
cookie = cookies.get(i);
String cookieName = cookie.getName();
String cookieValue = cookie.getValue();
if (!TextUtils.isEmpty(cookieName)
&& !TextUtils.isEmpty(cookieValue)) {
sb.append(cookieName + "=");
sb.append(cookieValue + ";");
}
}
Log.e("cookie", sb.toString());
return sb.toString();
}
在登录成功时,获取cookie并保存到application:
AntsApplication.cookie = getCookieText();
2、在访问网页的Activity里面,再次对cookie进行设置
String token = SharedPreferencesUtils.getParam(this, "token", "");
String userId = SharedPreferencesUtils.getParam(this, "userId", "");
WebSettings setting = contentWeb.getSettings();
setting.setJavaScriptEnabled(true);
contentWeb.setWebViewClient(new MyWebViewClient());
// 注:下面的code写在WebView的Activity里
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setCookie(Constant.URL_getArcitleInfo + "?token="+token+"&id="+id, AntsApplication.cookie);
CookieSyncManager.getInstance().sync();
//加载网页,必须放在最底下
contentWeb.loadUrl(Constant.URL_getArcitleInfo + "?token="+token+"&id="+id);