当前位置:首页 > 开发 > 移动开发 > 正文

Android使用Asynchronous Http Client完成登录保存cookie的问题

发表于: 2014-07-30   作者:hotsunshine   来源:转载   浏览:
摘要: Asynchronous Http Client是android中非常好的异步请求工具 除了异步之外还有很多封装比如json的处理,cookie的处理 引用 Persistent Cookie Storage with PersistentCookieStore This library also includes a PersistentCookieStore whi
Asynchronous Http Client是android中非常好的异步请求工具
除了异步之外还有很多封装比如json的处理,cookie的处理

引用

Persistent Cookie Storage with PersistentCookieStore

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.

This is extremely useful if you want to use cookies to manage authentication sessions, since the user will remain logged in even after closing and re-opening your app.

First, create an instance of AsyncHttpClient:

AsyncHttpClient myClient = new AsyncHttpClient();
Now set this client’s cookie store to be a new instance of PersistentCookieStore, constructed with an activity or application context (usually this will suffice):
PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);

Any cookies received from servers will now be stored in the persistent cookie store.

To add your own cookies to the store, simply construct a new cookie and call addCookie:

BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");
newCookie.setVersion(1);
newCookie.setDomain("mydomain.com");
newCookie.setPath("/");
myCookieStore.addCookie(newCookie);

See the PersistentCookieStore Javadoc for more information.


开篇边有一句话描述“utomatically saves cookies to SharedPreferences storage ”
自动保存cookie到SharedPreferences 中

需要注意的一点是下面设置cookie的代码
PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);

必须在client发起请求之前执行,然后再去执行client的get或者post请求。做好设置之后,它在请求之后才会把返回http的head中获取cookie保存。
否则是无法保存的。

Android使用Asynchronous Http Client完成登录保存cookie的问题

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号