问题一、cookie同步问题
有一个需求,在android中需要通过webview打开h5页面,并且需要把登录状态带到h5页面中,可以通过给webview要加载的url设置cookie的方式,同步登录状态。代码如下:
public void synCookies(Context context, String url) {
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setCookie(url, cookies);//cookies是在HttpClient中获得的cookie
String c = cookieManager.getCookie(url);
Log.v(TAG,"=======cookies"+c);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
CookieSyncManager.createInstance(getApplicationContext());
CookieSyncManager.getInstance().sync();
} else {
cookieManager.flush();
}
}
这里当时遇到一个问题,看别人写的会在setCookie(url,cookies)之前调用cookieManager.removeSessionCookies()方法清除cookie。
这种情况下在android4.3的真机和模拟器上均会出现登录状态同步失败的问题。
去查看源码发现,cookieManager.removeSessionCookie();
/**
* Removes all session cookies, which are cookies without an expiration
* date.
* <p>
* This method is asynchronous.
* If a {@link ValueCallback} is provided,
* {@link ValueCallback#onReceiveValue(T) onReceiveValue()} will be called on the current
* thread's {@link android.os.Looper} once the operation is complete.
* The value provided to the callback indicates whether any cookies were removed.
* You can pass {@code null} as the callback if you don't need to know when the operation
* completes or whether any cookie were removed, and in this case it is safe to call the
* method from a thread without a Looper.
* @param callback a callback which is executed when the session cookies have been removed
*/
public abstract void removeSessionCookies(ValueCallback<Boolean> callback);
此方法会清除没有过期时间的cookie,(至于为什么没有同步成功,还没弄清楚)如果想清除cookie可以调用removeAllCookie(),这时就可以同步成功了。
另外也可以不调用此方法,因为调用setCookie()的时候,会把原来的相同的cookie替换掉。