Android Cookie持久化
2019-10-23 本文已影响0人
大佬的上半生
Cookie
起源
- 网景公司当时一名员工Lou Montulli,在1994年将“cookies”的概念应用于网络通信,用来解决用户网上购物的购物车历史记录,目前所有浏览器都支持cookies。
cookie是什么?
由于http是无状态的协议,一旦客户端和服务器的数据交换完毕,就会断开连接,再次请求,会重新连接,这就说明服务器单从网络连接上是没有办法知道用户身份的。怎么办呢?那就给每次新的用户请求时,给它颁发一个身份证(独一无二)吧,下次访问,必须带上身份证,这样服务器就会知道是谁来访问了,针对不同用户,做出不同的响应。,这就是Cookie的原理。
其实cookie是一个很小的文本文件,是浏览器储存在用户的机器上的。Cookie是纯文本,没有可执行代码。储存一些服务器需要的信息,每次请求站点,会发送相应的cookie,这些cookie可以用来辨别用户身份信息等作用。
作用:
- 会话管理,登陆状态,购物车
- 个性化:用户偏好
- 会话管理,登陆状态,购物车
比如说IC卡
- 银行卡里存身份信息,公交卡存的信息,每次上对应的机器上就能从IC卡读取到信息认证方便操作
Android对cookie的持久化演示
cookie对象
public class CookieBean {
private String host;
private String name;
private String value;
private long expiresAt;
private String domain;
private String path;
private boolean secure;
private boolean httpOnly;}
cookie管理器
public class CookiesManager implements CookieJar {
private final PersistentCookieStore cookieStore = new PersistentCookieStore(GameCenterApp.getApplication());
@Override
public void saveFromResponse(@NonNull HttpUrl url, @NonNull List<Cookie> cookies) {
if(cookies.size() > 0) {
for(Cookie item : cookies) {
cookieStore.add(url, item);
}
}
}
@NonNull
@Override
public List<Cookie> loadForRequest(@NonNull HttpUrl url) {
return cookieStore.get(url);
}
//清除所有cookie
public void removeAllCookie() {
cookieStore.removeAll();
}}
持久化处理cookie
public class PersistentCookieStore {
private static final String LOG_TAG = "PersistentCookieStore";
private static final String COOKIE_PREFS = "Cookies_Prefs_Game_Center";
private finalMap<String, ConcurrentHashMap<String, Cookie>> cookies;
private finalSharedPreferences cookiePrefs;
PersistentCookieStore(Context context) {
cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, Context.MODE_PRIVATE);
cookies = new LinkedHashMap<>();
//将持久化的cookies缓存到内存中 即map cookies
Map<String, ?> prefsMap = cookiePrefs.getAll();
for(Map.Entry<String, ?> entry : prefsMap.entrySet()) {
String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
for(String name : cookieNames) {
String encodedCookie = cookiePrefs.getString(name, null);
if(encodedCookie != null) {
Cookie cookie = decodeCookie(encodedCookie);
if(cookie != null) {
String host = entry.getKey();
refreshUserLocalCookie(host, cookie);
LogUtil.d(LOG_TAG, "init: host="+host+", cookie="+cookie.toString());
if(!cookies.containsKey(host)) {
cookies.put(host, new ConcurrentHashMap<>());
}
ConcurrentHashMap<String, Cookie> map = cookies.get(host);
if(map != null) map.put(name, cookie);
}
}
}
}
}
private String getCookieToken(Cookie cookie) {
return cookie.name()+"@"+cookie.domain();
}
public void add(HttpUrl url, Cookie cookie) {
if(url == null || cookie == null) return;
String host = url.host();
LogUtil.d(LOG_TAG, "add: host="+host+", cookie="+cookie.toString());
String name = getCookieToken(cookie);
//将cookies缓存到内存中 如果缓存过期 就重置此cookie
if(!cookie.persistent()) {
if(!cookies.containsKey(host)) {
cookies.put(host, new ConcurrentHashMap<>());
}
ConcurrentHashMap<String, Cookie> map = cookies.get(host);
if(map != null) map.put(name, cookie);
} else {
if(cookies.containsKey(host)) {
ConcurrentHashMap<String, Cookie> map = cookies.get(host);
if(map != null) map.remove(name);
}
}
//讲cookies持久化到本地
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
ConcurrentHashMap<String, Cookie> map = cookies.get(host);
if(map != null) {
refreshUserLocalCookie(host, cookie);
prefsWriter.putString(host, TextUtils.join(",", map.keySet()));
prefsWriter.putString(name, encodeCookie(new SerializableOkHttpCookies(cookie)));
prefsWriter.commit();
}
String value = cookie.name()+"="+cookie.value();
CookieManager.getInstance().setCookie(url.toString(), value);
}
public List<Cookie> get(HttpUrl url) {
ArrayList<Cookie> ret = new ArrayList<>();
if(url != null) {
String host = url.host();
if(cookies.containsKey(host)) {
ConcurrentHashMap<String, Cookie> map = cookies.get(host);
if(map != null) {
ret.addAll(map.values());
}
}
}
return ret;
}
void removeAll() {
cookiePrefs.edit().clear().commit();
cookies.clear();
CookieManager.getInstance().removeAllCookie();
}
public boolean remove(HttpUrl url, Cookie cookie) {
if(url == null || cookie == null) return false;
String host = url.host();
LogUtil.d(LOG_TAG, "remove: host="+host+", cookie="+cookie.toString());
String name = getCookieToken(cookie);
refreshUserLocalCookie(host, cookie);
if(cookies.containsKey(host) && cookies.get(host).containsKey(name)) {
cookies.get(host).remove(name);
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
if(cookiePrefs.contains(name)) {
prefsWriter.remove(name);
}
prefsWriter.putString(host, TextUtils.join(",", cookies.get(host).keySet()));
prefsWriter.apply();
return true;
} else {
return false;
}
}
public List<Cookie> getCookies() {
ArrayList<Cookie> ret = new ArrayList<>();
for(String key : cookies.keySet())
ret.addAll(cookies.get(key).values());
return ret;
}
//同步cookie
private void refreshUserLocalCookie(String host, Cookie cookie) {
if("USER_SESSIONID".equalsIgnoreCase(cookie.name())) {
CookieBean cookieBean = new CookieBean();
cookieBean.setHost(host);
cookieBean.setName(cookie.name());
cookieBean.setValue(cookie.value());
cookieBean.setExpiresAt(cookie.expiresAt());
cookieBean.setDomain(cookie.domain());
cookieBean.setPath(cookie.path());
cookieBean.setSecure(cookie.secure());
cookieBean.setHttpOnly(cookie.httpOnly());
UserInfoManager.refreshCookie(cookieBean);
}
}
/**
* cookies 序列化成 string
*
* @param cookie 要序列化的cookie
*
* @return 序列化之后的string
*/
private String encodeCookie(SerializableOkHttpCookies cookie) {
if(cookie == null) return null;
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ObjectOutputStream outputStream = new ObjectOutputStream(os);
outputStream.writeObject(cookie);
} catch(IOException e) {
Log.d(LOG_TAG, "IOException in encodeCookie", e);
return null;
}
return byteArrayToHexString(os.toByteArray());
}
/**
* 将字符串反序列化成cookies
*
* @param cookieString cookies string
*
* @return cookie object
*/
private Cookie decodeCookie(String cookieString) {
byte[] bytes = hexStringToByteArray(cookieString);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
Cookie cookie = null;
try {
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
cookie = ((SerializableOkHttpCookies) objectInputStream.readObject()).getCookies();
} catch(IOException e) {
Log.d(LOG_TAG, "IOException in decodeCookie", e);
} catch(ClassNotFoundException e) {
Log.d(LOG_TAG, "ClassNotFoundException in decodeCookie", e);
}
return cookie;
}
/**
* 二进制数组转十六进制字符串
*
* @param bytes byte array to be converted
*
* @return string containing hex values
*/
private String byteArrayToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length*2);
for(byte element : bytes) {
int v = element&0xff;
if(v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase(Locale.US);
}
/**
* 十六进制字符串转二进制数组
*
* @param hexString string of hex-encoded values
*
* @return decoded byte array
*/
private byte[] hexStringToByteArray(String hexString) {
int len = hexString.length();
byte[] data = new byte[len/2];
for(int i = 0; i < len; i += 2) {
data[i/2] = (byte) ((Character.digit(hexString.charAt(i), 16)<<4)+Character.digit(hexString.charAt(i+1), 16));
}
return data;
}
}
public class SerializableOkHttpCookies implements Serializable {
private transient final Cookie cookies;
private transient Cookie clientCookies;
public SerializableOkHttpCookies(Cookie cookies) {
this.cookies = cookies;
}
public Cookie getCookies() {
Cookie bestCookies = cookies;
if(clientCookies != null) {
bestCookies = clientCookies;
}
return bestCookies;
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(cookies.name());
out.writeObject(cookies.value());
out.writeLong(cookies.expiresAt());
out.writeObject(cookies.domain());
out.writeObject(cookies.path());
out.writeBoolean(cookies.secure());
out.writeBoolean(cookies.httpOnly());
out.writeBoolean(cookies.hostOnly());
out.writeBoolean(cookies.persistent());
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
String name = (String) in.readObject();
String value = (String) in.readObject();
long expiresAt = in.readLong();
String domain = (String) in.readObject();
String path = (String) in.readObject();
boolean secure = in.readBoolean();
boolean httpOnly = in.readBoolean();
boolean hostOnly = in.readBoolean();
boolean persistent = in.readBoolean();
Cookie.Builder builder = new Cookie.Builder();
builder = builder.name(name);
builder = builder.value(value);
builder = builder.expiresAt(expiresAt);
builder = hostOnly ? builder.hostOnlyDomain(domain) : builder.domain(domain);
builder = builder.path(path);
builder = secure ? builder.secure() : builder;
builder = httpOnly ? builder.httpOnly() : builder;
clientCookies = builder.build();
}
}