Android之CookieStore的持久化
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的持久化的更多相关文章
- Android中的数据持久化机制
Android中几种最简单但是却最通用的数据持久化技术:SharedPreference.实例状态Bundle和本地文件. Android的非确定性Activity和应用程序生存期使在会话间保留UI状 ...
- Android开发学习---android下的数据持久化,保存数据到rom文件,android_data目录下文件访问的权限控制
一.需求 做一个类似QQ登录似的app,将数据写到ROM文件里,并对数据进行回显. 二.截图 登录界面: 文件浏览器,查看文件的保存路径:/data/data/com.amos.datasave/fi ...
- Android 使用Okhttp/Retrofit持久化cookie的简便方式
首先cookie是什么就不多说了,还是不知道的话推荐看看这篇文章 Cookie/Session机制详解 深入解析Cookie技术 为什么要持久化cookie也不多说了,你能看到这篇文章代表你有这个需求 ...
- Android学习_数据持久化
数据持久化:将内存中的瞬时数据存储到设备中 1. 文件存储 存储一些简单的文本数据或二进制数据. 核心:Context类提供的openFileOutput()和openFileInput()方法,然后 ...
- Android 4 学习(15):持久化:Files, Saving State and Preferences
参考<Professional Android 4 Development> 持久化:Files, Saving State and Preferences Android中的数据持久化 ...
- Android数据库加密之sqlciher方案
版权声明:本文为博主原创文章,未经博主允许不得转载. 转载请表明出处:http://www.cnblogs.com/cavalier-/p/6241964.html 前言 大家好,我是Cavalier ...
- android: 文件存储
数据持久化就是指将那些内存中的瞬时数据保存到存储设备中,保证即使在手机或电脑 关机的情况下,这些数据仍然不会丢失.保存在内存中的数据是处于瞬时状态的,而保存在 存储设备中的数据是处于持久状态的,持久化 ...
- 我的Android进阶之旅------>经典的大牛博客推荐(排名不分先后)!!
本文来自:http://blog.csdn.net/ouyang_peng/article/details/11358405 今天看到一篇文章,收藏了很多大牛的博客,在这里分享一下 谦虚的天下 柳志超 ...
- 我的Android 4 学习系列之文件、保存状态和首选项
目录 使用Shared Preference 保留简单的应用程序数据 保存回话间的Activity实例数据 管理应用程序首选项和创建Preference Screen 保存并加载文件以及管理本地文件系 ...
随机推荐
- 关于fsockopen pfsockopen函数被禁用的解决方法
服务器同时禁用了fsockopen pfsockopen,那么用其他函数代替,如stream_socket_client().注意:stream_socket_client()和fsockopen() ...
- MySQL恢复备份读书笔记
1. 任何执行时间长于 wait_timeout或interactive_timeout选项值得备份,都会导致会话被关闭,这也会隐含执行UNLOCK TABLES命令.2. 对于使用FLUSH TAB ...
- Centos查看端口占用情况和开启端口命令
Centos查看端口占用情况命令,比如查看80端口占用情况使用如下命令: lsof -i tcp:80 列出所有端口 netstat -ntlp 1.开启端口(以80端口为例)方法一: /sbin/i ...
- Gesture(手势)浅析
1.Gesture的作用 ①在触摸屏上的连续触摸行为,形成某个方向上的移动趋势 (利用手势检测) ②连续画出一个不规则的行为 (利用增加手势) 2.手势检测(GestureDetector) // ...
- cordova开发中遇到的一些坑
# 外域的JS被禁止,修改meta标签 <meta http-equiv="Content-Security-Policy" content="default-sr ...
- Noldbach problem
Description Noldbach problem time limit per test: 2 seconds memory limit per test: 64 megabytes inpu ...
- MYSQ 查看 2 进制日志
方法 1: myqlbinlog filename; ------------------------------------------------------------------------- ...
- J2SE知识点摘记(五)
1. 引用数据类型的传递 java用引用代替C++中的指针 fun()方法接收的参数是是Change c1,也就是说说fun()方法接受的是一个对象的引用,所以fun方法中所所做的操作就 ...
- css案例学习之父子块的margin
两边还会有些距离,这是body默认的. 代码: <head> <title>父子块的margin</title> <style type="text ...
- poj3094---对字符串的处理
#include <stdio.h> #include <stdlib.h> #include<string.h> int main() { ]; int len, ...