Android之CookieStore的持久化【转载】

CookieStore是一个对象,有的服务端 ,比如.net,保持登录状态不是用httpclient.addHeader(“cookie”,SessionId),而是用

httppost.setCookieStore(cokkieStore).SessionId存储很方便,就一串字符串,可直接储存唉SharedPreference里即可,那么对于CookieStore对象的存储无疑成了难题

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
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 *  2 );
for ( byte element : b) {
int v = element &  0xff ;
if (v <  16 ) {
sb.append( '0' );
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase();
}
 
protected byte [] hexStringToByteArray(String s) {
int len = s.length();
byte [] data =  new byte [len /  2 ];
for ( int i =  0 ; i < len; i +=  2 ) {
data[i /  2 ] = ( byte ) ((Character.digit(s.charAt(i),  16 ) <<  4 ) + Character.digit(s.charAt(i +  1 ),  16 ));
}
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());
}
}
}

存储方法如下:

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

这样就实现了持久化存储

使用方如下:

1
2
3
PreferencesCookieStore cookieStore =  new PreferencesCookieStore(App.getInstance().getApplicationContext());
 
httpClient.setCookieStore(cookieStore);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值