CookieStore是一个对象,有的服务端 ,比如.net,保持登录状态不是用httpclient.addHeader(“cookie”,SessionId),而是用httppost.setCookieStore(cokkieStore).SessionId存储很方便,就一串字符串,可直接储存唉SharedPreference里即可,那么对于CookieStore对象的存储无疑成了难题

存储方法:自定义一个类,继承CookieStore

public class PreferencesCookieStore implements CookieStore {

private static final String COOKIE_PREFS = "CookiePrefsFile";
private static final String COOKIE_NAME_STORE = "names";
private static final String COOKIE_NAME_PREFIX = "cookie_"; private final ConcurrentHashMap<String, Cookie> cookies;
private final SharedPreferences cookiePrefs; /**
* Construct a persistent cookie store.
*/
public PreferencesCookieStore(Context context) {
cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, Context.MODE_PRIVATE);
cookies = new ConcurrentHashMap<String, Cookie>(); // Load any previously stored cookies into the store
String storedCookieNames = cookiePrefs.getString(COOKIE_NAME_STORE, null);
if (storedCookieNames != null) {
String[] cookieNames = TextUtils.split(storedCookieNames, ",");
for (String name : cookieNames) {
String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
if (encodedCookie != null) {
Cookie decodedCookie = decodeCookie(encodedCookie);
if (decodedCookie != null) {
cookies.put(name, decodedCookie);
}
}
} // Clear out expired cookies
clearExpired(new Date());
}
} @Override
public void addCookie(Cookie cookie) {
String name = cookie.getName(); // Save cookie into local store, or remove if expired
if (!cookie.isExpired(new Date())) {
cookies.put(name, cookie);
} else {
cookies.remove(name);
} // Save cookie into persistent store
SharedPreferences.Editor editor = cookiePrefs.edit();
editor.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));
editor.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie)));
editor.commit();
} @Override
public void clear() {
// Clear cookies from persistent store
SharedPreferences.Editor editor = cookiePrefs.edit();
for (String name : cookies.keySet()) {
editor.remove(COOKIE_NAME_PREFIX + name);
}
editor.remove(COOKIE_NAME_STORE);
editor.commit(); // Clear cookies from local store
cookies.clear();
} @Override
public boolean clearExpired(Date date) {
boolean clearedAny = false;
SharedPreferences.Editor editor = cookiePrefs.edit(); for (ConcurrentHashMap.Entry<String, Cookie> entry : cookies.entrySet()) {
String name = entry.getKey();
Cookie cookie = entry.getValue();
if (cookie.getExpiryDate() == null || cookie.isExpired(date)) {
// Remove the cookie by name
cookies.remove(name); // Clear cookies from persistent store
editor.remove(COOKIE_NAME_PREFIX + name); // We've cleared at least one
clearedAny = true;
}
} // Update names in persistent store
if (clearedAny) {
editor.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));
}
editor.commit(); return clearedAny;
} @Override
public List<Cookie> getCookies() {
return new ArrayList<Cookie>(cookies.values());
} public Cookie getCookie(String name) {
return cookies.get(name);
}
protected String encodeCookie(SerializableCookie cookie) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ObjectOutputStream outputStream = new ObjectOutputStream(os);
outputStream.writeObject(cookie);
} catch (Throwable e) {
return null;
} return byteArrayToHexString(os.toByteArray());
} protected Cookie decodeCookie(String cookieStr) {
byte[] bytes = hexStringToByteArray(cookieStr);
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
Cookie cookie = null;
try {
ObjectInputStream ois = new ObjectInputStream(is);
cookie = ((SerializableCookie) ois.readObject()).getCookie();
} catch (Throwable e) {
LogUtils.e(e.getMessage(), e);
} return cookie;
} // Using some super basic byte array <-> hex conversions so we don't have
// to rely on any large Base64 libraries. Can be overridden if you like!
protected String byteArrayToHexString(byte[] b) {
StringBuffer sb = new StringBuffer(b.length * );
for (byte element : b) {
int v = element & 0xff;
if (v < ) {
sb.append('');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase();
} protected byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / ];
for (int i = ; i < len; i += ) {
data[i / ] = (byte) ((Character.digit(s.charAt(i), ) << ) + Character.digit(s.charAt(i + ), ));
}
return data;
}
public class SerializableCookie implements Serializable {
private static final long serialVersionUID = 6374381828722046732L; private transient final Cookie cookie;
private transient BasicClientCookie clientCookie; public SerializableCookie(Cookie cookie) {
this.cookie = cookie;
} public Cookie getCookie() {
Cookie bestCookie = cookie;
if (clientCookie != null) {
bestCookie = clientCookie;
}
return bestCookie;
} private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(cookie.getName());
out.writeObject(cookie.getValue());
out.writeObject(cookie.getComment());
out.writeObject(cookie.getDomain());
out.writeObject(cookie.getExpiryDate());
out.writeObject(cookie.getPath());
out.writeInt(cookie.getVersion());
out.writeBoolean(cookie.isSecure());
} private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
String name = (String) in.readObject();
String value = (String) in.readObject();
clientCookie = new BasicClientCookie(name, value);
clientCookie.setComment((String) in.readObject());
clientCookie.setDomain((String) in.readObject());
clientCookie.setExpiryDate((Date) in.readObject());
clientCookie.setPath((String) in.readObject());
clientCookie.setVersion(in.readInt());
clientCookie.setSecure(in.readBoolean());
}
}
}

存储方法如下:

/* 获取并保存Cookie值 */
cookieStore = httpClient.getCookieStore();
List<Cookie> cookies = httpClient.getCookieStore().getCookies(); // 持久化CookieStore
PreferencesCookieStore preferencesCookieStore = new PreferencesCookieStore(
context);
for (Cookie cookie : cookies) {
preferencesCookieStore.addCookie(cookie);
}

这样就实现了持久化存储

使用方如下:

PreferencesCookieStore cookieStore = new PreferencesCookieStore(App.getInstance().getApplicationContext());
httpClient.setCookieStore(cookieStore);

Android之CookieStore的持久化的更多相关文章

  1. Android中的数据持久化机制

    Android中几种最简单但是却最通用的数据持久化技术:SharedPreference.实例状态Bundle和本地文件. Android的非确定性Activity和应用程序生存期使在会话间保留UI状 ...

  2. Android开发学习---android下的数据持久化,保存数据到rom文件,android_data目录下文件访问的权限控制

    一.需求 做一个类似QQ登录似的app,将数据写到ROM文件里,并对数据进行回显. 二.截图 登录界面: 文件浏览器,查看文件的保存路径:/data/data/com.amos.datasave/fi ...

  3. Android 使用Okhttp/Retrofit持久化cookie的简便方式

    首先cookie是什么就不多说了,还是不知道的话推荐看看这篇文章 Cookie/Session机制详解 深入解析Cookie技术 为什么要持久化cookie也不多说了,你能看到这篇文章代表你有这个需求 ...

  4. Android学习_数据持久化

    数据持久化:将内存中的瞬时数据存储到设备中 1. 文件存储 存储一些简单的文本数据或二进制数据. 核心:Context类提供的openFileOutput()和openFileInput()方法,然后 ...

  5. Android 4 学习(15):持久化:Files, Saving State and Preferences

    参考<Professional Android 4 Development> 持久化:Files, Saving State and Preferences Android中的数据持久化 ...

  6. Android数据库加密之sqlciher方案

    版权声明:本文为博主原创文章,未经博主允许不得转载. 转载请表明出处:http://www.cnblogs.com/cavalier-/p/6241964.html 前言 大家好,我是Cavalier ...

  7. android: 文件存储

    数据持久化就是指将那些内存中的瞬时数据保存到存储设备中,保证即使在手机或电脑 关机的情况下,这些数据仍然不会丢失.保存在内存中的数据是处于瞬时状态的,而保存在 存储设备中的数据是处于持久状态的,持久化 ...

  8. 我的Android进阶之旅------>经典的大牛博客推荐(排名不分先后)!!

    本文来自:http://blog.csdn.net/ouyang_peng/article/details/11358405 今天看到一篇文章,收藏了很多大牛的博客,在这里分享一下 谦虚的天下 柳志超 ...

  9. 我的Android 4 学习系列之文件、保存状态和首选项

    目录 使用Shared Preference 保留简单的应用程序数据 保存回话间的Activity实例数据 管理应用程序首选项和创建Preference Screen 保存并加载文件以及管理本地文件系 ...

随机推荐

  1. 前端开发面试题收集 JS

    前端开发面试题收集-JS篇 收集经典的前端开发面试题 setTimeout的时间定义为0有什么用? javascript引擎是单线程处理任务的,它把任务放在队列中,不会同步执行,必须在完成一个任务后才 ...

  2. Linux--正则表达式--详解

    一.linux文本查找命令 在说linux正规表达式之前,还介绍下linux中查找文本文件常用的三个命令: 1.grep : 最早的文本匹配程序,使用POSIX定义的基本正则表达式(BRE)来匹配文本 ...

  3. Python之路第五天,基础(5)-序列化和字符串格式化

    序列化 Python中用于序列化的两个模块 json 用于『字符串』和『python基本数据类型』间进行转换 pickle 用于『python特有的类型』和『python基本数据类型』间进行转换 js ...

  4. LinkList的实现

    public class MyLinkedList<AnyType> implements Iterable<AnyType> { @Override public Itera ...

  5. Ghost win7 系统安装(虚拟机)

    1.将Ghost.iso添加到数据存储iso文件中,启动虚拟机,根据相关提示,文件格式化系统硬盘,完成操作后关机: 2.进入BIOS,设置从CDROM启动系统(否则系统会提示找到引导文件): 3.将系 ...

  6. ThinkPHP框架下基于RBAC的权限控制模式详解

    这几天因为要做一个项目,需要可以对Web应用中通用功能进行封装,其中一个很重要的涉及到了对用户.角色和权限部分的灵活管理.所以基于TP框架自己封装了一个对操作权限和菜单权限进行灵活配置的可控制模式. ...

  7. ASP.net MVC3里的HandleErrorAttribute

    在MVC3里使用HandleErrorAttribte类,有2种方式可以使用它,一是在类或者方法上直接使用HandleError属性来定义: // 在这里声明[HandleError]public c ...

  8. logstash 根据type 判断输出

    # 更多ELK资料请访问 http://devops.taobao.com 一.配置前需要注意: 1.Use chmod to modify nginx log file privilege. E.g ...

  9. LINQpad 用法汇总

    // C# Expression //Courses // .Join ( // CourseSections, // course => course.CourseId, // section ...

  10. AndroidUI 视图动画-旋转动画效果 (RotateAnimation)

    RotateAnimation,能实现Android的视图的旋转效果,废话不多说直接上代码. 新建一个Android 项目,在activity_main.xml中添加一个按钮,然后使用Relative ...