AsyncHttpClient的CookieStore问题

转自:http://www.xuebuyuan.com/1595673.html

看来好多的文章都说asyncHttpClient中对cookies进行了自动化保存,你很容易的觉得他是将cookies保存到了你的http的请求中,其实不是这样的。

我查看了一下官方的文档这样说的

This library also includes a PersistentCookieStore which
is an implementation of the Apache HttpClient 
CookieStore interface
that automatically saves cookies to 
SharedPreferences storage
on the Android device.

他大概意思是将coolies自动保存到了首选项中。

然后我做了一个测试

AsyncHttpClient client = AsyncHttpCilentUtil.getInstence();
		HttpContext httpContext = client.getHttpContext();
		CookieStore cookies = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);//获取AsyncHttpClient中的CookieStore
		if(cookies!=null){
			for(Cookie c:cookies.getCookies()){
				LogUtil.d("main before ~~"+c.getName(),c.getValue());
			}
		}else{
			LogUtil.d("main  before~~","cookies is null");
		}
		PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
		client.setCookieStore(myCookieStore);
		httpContext = client.getHttpContext();
		cookies = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);
		if(cookies!=null){
			for(Cookie c:cookies.getCookies()){
				LogUtil.d("main after ~~"+c.getName(),c.getValue());
			}
		}else{
			LogUtil.d("main  after~~","cookies is null");
		}

打印log你会发现main before中打印的是没有值的,after中才有值。


这说明了需要我们手动的去设置,不然你提交给服务端是没有提交先关cookies的。

在来说说cookies是从什么时候开始有的。

首先我在注册时打印了一下coolies的空的(说明一下我每次在结束app时都会cookieStore.clear();一下,不然他会将上一次的带入,特别是服务端有自动登录的情况,容易导致获取数据的错误),然后接着在注册成功跳转的页面中(就是上面提到的)。


其实coolies的获取就是在你服务器返回成功后,AsyncHttpClient会获取到你的cookies然后自动保存到你的首选项中,这时候只需要我们手动set一下即可,这样就保持了和服务端的session一致问题,也不会导致出现401权限错误。

PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
client.setCookieStore(myCookieStore);


你可能感兴趣的:(android,cookie,AsyncHttpClient)