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. eclipse 使用maven 创建springmvc + mybatis

    接着eclipse 使用maven 创建纯spring mvc项目 毕竟项目都要访问数据库的, 所以加上mybatis的支持也就是网上大多时候说的 SSM框架的搭建(Spring + Spring M ...

  2. 表格(table) 插件:支持当前行增行、删除。使用事件委托

    最近做一个项目,需要对表格进行增行和删行. 研究了一下jquery操作dom的方法和事件委托原理,下面是我编写的例子,源码传上,欢迎高手指点. 功能: 支持在指定行下面增行: 支持删行指定行: 增行. ...

  3. 关于Git和Github

    英文原文:Ten Things You Didn't Know Git And GitHub Could Do Git 和 GitHub 都是非常强大的工具.即使你已经使用他们很长时间,你也很有可能不 ...

  4. Oracle 11g R2安装手册(图文教程)For Windows

    1.Oracle 11g R2安装手册(图文教程)For Windows 1.下载Oracle 11g R2 for Windows版本,下载地址如下 官方网站: http://download.or ...

  5. Web学习

    http://book.2cto.com/201309/31936.html http://alvinalexander.com/ 查看锁表进程SQL语句1: select sess.sid,     ...

  6. Delphi下创建异形窗体

    procedure TForm1.FormCreate(Sender: TObject);var  pt: array [0 .. 4] of TPoint;  m_rgn: HRGN;begin   ...

  7. delphi 打开文件夹并定位到一个文件(使用ShellExecute时加一个select参数,原来这么简单!)

    strFileName := FcxLV[nIndex].Items.Item[FcxLV[nIndex].ItemIndex].SubItems.Strings[0]; //路径  ShellExe ...

  8. GIS 地图中术语解释

    分辨率和像素的关系 像素是指照片的点数(表示照片是由多少点构成的),分辨率是指照片像素点的密度(是用单位尺寸内的像素点,一般用每英寸多少点表示--dpi).照片实际大小是像素决定的.一个像素很大的照片 ...

  9. css的绝对定位

    假设绝对定位的元素的id为absoluteDiv. 当包含absoluteDiv的块中没有设置position:relative时, absoluteDiv会相对于浏览器(window.top)定位. ...

  10. 跟我一起学extjs5(24--模块Form的自己定义的设计[2])

    跟我一起学extjs5(24--模块Form的自己定义的设计[2])         在本节中将要增加各种类型的字段,在增加字段的时候因为能够一行增加多个字段,因此层次结构又多了一层fieldcont ...