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. [ZT]DAS\NAS\IP SAN\FC SAN之区别

    DAS:服务器直接后挂存储设备,最经济的一种结构. NAS:网络上直接挂接的存储设备,其实就是处于以太网上的一台利用NFS.CIFS等网络文件系统的文件共享服务器. SAN是网络上的磁盘,NAS是一个 ...

  2. 在MySQL数据库建立多对多的数据表关系

    在数据库中,如果两个表的之间的关系为,多对多的关系,如:“学生表和课程表”,一个学生的可以选多门课,一门课也可以被多门学习选;根据数据库的设计原则,应当形成第三张关联表 步骤1:创建三张数据表Stud ...

  3. Java数据结构习题_算法分析

    2.设T1(N)=O(f(N)),T2(N)=O(f(N)),则: T1(N)-T2(N)=o(f(N))           False,若1位2N,2为N T1(N)/T2(N)=O(1)     ...

  4. leetcode算法刷题(四)——动态规划(二)

    又到了晚上,动态规划,开刷! 第121题 Best Time to Buy and Sell Stock 题目的意思:给予一个数组price,表示特定股票在某天的股价,里面第i个数表示第i天的价格.只 ...

  5. OpenCV2.4.9+VS2012安装与配置

    需要下载并安装Visual Studio 2012 然后在OpenCV官网下载安装OpenCV2.4.9 for Windows,网址为http://opencv.org/downloads.html ...

  6. NET Core 介绍

    NET Core 介绍 标签: ASP.NETCore 1. 前言 2. ASP.NET Core 简介 2.1 什么是ASP.NET Core 2.2 ASP.NET Core的特点 2.3 ASP ...

  7. SQL Server 数据库的自动选项

    自动选项影响SQL Server 可能会自动进行的操作,所有的这些都是bool值,值为on 或off 1. auto_close: 当这个为on 时.数据库在最后一个用户退出后完全关闭,这样数据库就不 ...

  8. centos6.5图形界面NetworkManager 配置ip文件位置

    请教一个关于网络配置的问题,如图:该网络连接图形界面中 有2个配置,其中System eth0 有对应的配置文件/etc/sysconfig/network-scripts/ifcfg-eth0,但是 ...

  9. 使用Task简化Silverlight调用Wcf

    原文http://www.cnblogs.com/lemontea/archive/2012/12/09/2810549.html 从.Net4.0开始,.Net提供了一个Task类来封装一个异步操作 ...

  10. java线程管理

    java线程管理 参见: http://harmony.apache.org/subcomponents/drlvm/TM.html 1. 修订历史 2. 关于本文档 2.1. 目的 2.2. 面向的 ...