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. Kernel Packet Traveling Diagram(图片,关于iptables)

    转自:view-source:http://www.docum.org/docum.org/kptd/ Network -----------+----------- | +------------- ...

  2. 实现mysql的分组排名问题

    如下图所示的表结构,mysql中查出按照相同class的成员按照年龄排序. sql语句实现如下: SELECT id,name,age,rank FROM ( ,) AS rank,@pa:=ff.c ...

  3. title:EL表达式获取Map里面的数值失败的问题

    在控制器中定义了一个Map<Integer,String>集合,看似没有问题,将这个集合的对象map传递到一个JSP页面中,我们都知道,用EL表达式 ${map[key]}就可以取得key ...

  4. 菜鸟的jQuery源码学习笔记(三)

    each: function(callback, args) { return jQuery.each(this, callback, args); }, each:这个调用了jQuery.each方 ...

  5. 动手编写插件-javascript分页插件

    原来公司用的报表分页插件是C#编写的服务器插件,需要前后台交互,而且不支持ajax. 经过一段时间折腾,我编写了一个轻便的jquery分页插件,支持ajax.下面是插件代码 /* 插件名称:报表分页 ...

  6. 使用pymysql和paramiko实现远程安装软件

    通过pymysql模块调用数据库获取安装信息,通过paramiko模块远程传输脚本并执行来安装软件,本文以安装apache为例. 创建apache安装信息数据表install_apache,设定三个字 ...

  7. 通宵疯狂积累VB.NET基础知识

    VB.NET中Module的概念 为什么VB.NET中会有一个Module的东西,而在C#等语言中是没有的 首先,这是一个历史原因.早先的VB语言都有模块和类模块的概念.所谓模块一般就是存放公用的一些 ...

  8. Google的兼容包问题【转】

    转自:http://blog.sina.com.cn/s/blog_3e28c8a50101g14g.html 项目之前好好的,今天开Eclipse,,出错. 错误Error retrieving p ...

  9. Risk(最短路)

    Risk Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 2915   Accepted: 1352 Description ...

  10. android入门——数据存储

    首先是SharedPreferences 用户偏好 package com.example.wkp.aboutdata; import android.content.Intent; import a ...