AsyncHttpClient的CookieStore问题

看来好多的文章都说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);

还有一点请注意,最开始我在每一次用AsyncHttpClient是都new了一个新的对象,这样导致登录后,和请求的数据不是同一个对象,也会导致报401的权限问题,解决方式

编写一个单例

public class AsyncHttpCilentUtil {

	private static AsyncHttpClient client = null;
	
	public synchronized static AsyncHttpClient getInstence(){
		if(client ==null){
			client = new AsyncHttpClient();
			client.setTimeout(1000*10);
		}
		return client;
	}
	
}



如果有错误,还望大家指正




  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值