百度了很多,但是大都是同样的代码
public void synCookies( String url,String cookie) {
CookieSyncManager.createInstance(UiUtils.getContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setCookie(url, cookie);
CookieSyncManager.getInstance().sync();
}
这样肯定没错,但是很多情况下,它不起作用。
首先,最好先清空cookie,防止切换用户导致cookie混乱。
其次,当cookie的信息不止一条是,上面的代码是失效的。
还有,如果存在path,和domain,需要带回去,拼接的时候用分号拼接,通过StringBuilder的方式合成一个字符串。
多个cookie信息,一定要分开对应自己的path和domain,for循环,多次setCookie。
public static void synCookies(Context context,String url,List<Cookie> cookies){
if ( !TextUtils.isEmpty(url) )
if (!TextUtils.isEmpty(cookies) ) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
CookieSyncManager.createInstance( context);
}
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie( true );
cookieManager.removeSessionCookie();// 移除
cookieManager.removeAllCookie();
StringBuilder sbCookie = new StringBuilder();//创建一个拼接cookie的容器,
for (Cookie cookie : cookies) {
sbCookie.append(cookie.name()+"="+cookie.value());
sbCookie.append(";domain="+cookie.domain());
sbCookie.append(";path="+cookie.path());
String cookieValue = sbCookie.toString();
cookieManager.setCookie(url, cookieValue);//为url设置cookie
}
CookieSyncManager.getInstance().sync();//同步cookie
String newCookie = cookieManager.getCookie(url);
LogManager.i("同步后cookie", newCookie);
}
}
这次遇到的坑是这样的,页面请求第一次的时候,cookie成功带过去了,但是页面内部请求有ajax请求时,发送到后台的cookie迷之消失了,也不知道是什么原因。
解决方法如下
拦截请求,在拦截中重新同步cookie
mProgressWebView.setWebViewClient(new CustomWebViewClient(mProgressWebView.getWebView()) {
/**
* 5.0以下
*/
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
synCookies(url);
return super.shouldInterceptRequest(view, url);//将加好cookie的url传给父类继续执行
}
/**
*5.0以上
*/
@SuppressLint("NewApi")
@Override
public WebResourceResponse shouldInterceptRequest(WebView view , WebResourceRequest request) {
String url = request.getUrl().toString();
synCookies(url);
return super.shouldInterceptRequest(view, url);
}
});
public static void synCookies(String url){
if ( !TextUtils.isEmpty(url) )
if (!TextUtils.isEmpty(SpUtils.getString(SpUtils.TOKEN)) ) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
CookieSyncManager.createInstance( UiUtils.getContext());
}
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie( true );
cookieManager.removeSessionCookie();// 移除
cookieManager.removeAllCookie();
StringBuilder sbCookie = new StringBuilder();
//应为我这里只传递一个oatoken = xxxxxxxxx;而且后台默认不用domain和path
sbCookie.append(SpUtils.getString(SpUtils.TOKEN));//拼接sessionId
// sbCookie.append(String.format(";domain=%s", ""));
// sbCookie.append(String.format(";path=%s", ""));
String cookieValue = sbCookie.toString();
cookieManager.setCookie(url, cookieValue);//为url设置cookie
CookieSyncManager.getInstance().sync();//同步cookie
String newCookie = cookieManager.getCookie(url);
}
}