參考:https://www.zhihu.com/question/19786827
http://www.open-open.com/lib/view/open1453422314105.html
COOKIE和SESSION 是什么氮发?隘截?野舶?
- 由于HTTP協(xié)議是無狀態(tài)的協(xié)議,所以服務(wù)端需要記錄用戶的狀態(tài)時,就需要用某種機制來識具體的用戶,這個機制就是Session.典型的場景比如購物車,當你點擊下單按鈕時谷炸,由于HTTP協(xié)議無狀態(tài),所以并不知道是哪個用戶操作的竖螃,所以服務(wù)端要為特定的用戶創(chuàng)建了特定的Session淑廊,用于標識這個用戶逗余,并且跟蹤用戶特咆,這樣才知道購物車里面有幾本書。這個Session是保存在服務(wù)端的录粱,有一個唯一標識腻格。在服務(wù)端保存Session的方法很多,內(nèi)存啥繁、數(shù)據(jù)庫菜职、文件都有。集群的時候也要考慮Session的轉(zhuǎn)移旗闽,在大型的網(wǎng)站酬核,一般會有專門的Session服務(wù)器集群,用來保存用戶會話适室,這個時候 Session 信息都是放在內(nèi)存的嫡意,使用一些緩存服務(wù)比如Memcached之類的來放 Session。
- 思考一下服務(wù)端如何識別特定的客戶捣辆?這個時候Cookie就登場了蔬螟。每次HTTP請求的時候,客戶端都會發(fā)送相應(yīng)的Cookie信息到服務(wù)端汽畴。實際上大多數(shù)的應(yīng)用都是用 Cookie 來實現(xiàn)Session跟蹤的旧巾,第一次創(chuàng)建Session的時候,服務(wù)端會在HTTP協(xié)議中告訴客戶端忍些,需要在 Cookie 里面記錄一個Session ID鲁猩,以后每次請求把這個會話ID發(fā)送到服務(wù)器,我就知道你是誰了罢坝。有人問绳匀,如果客戶端的瀏覽器禁用了 Cookie 怎么辦?一般這種情況下,會使用一種叫做URL重寫的技術(shù)來進行會話跟蹤疾棵,即每次HTTP交互戈钢,URL后面都會被附加上一個諸如 sid=xxxxx 這樣的參數(shù),服務(wù)端據(jù)此來識別用戶是尔。
在OkHttp3中殉了,對cookie而言,新增了兩個類Cookiejar
拟枚、 Cookie
兩個類薪铜,在了解這兩個類之前,先去看一下 HttpEngine
關(guān)于cookie管理的變化
private Request networkRequest(Request request) throws IOException {
Request.Builder result = request.newBuilder();
//例行省略....
List<Cookie> cookies = client.cookieJar().loadForRequest(request.url());
if (!cookies.isEmpty()) {
result.header("Cookie", cookieHeader(cookies));
}
//例行省略....
return result.build();
}
private String cookieHeader(List<Cookie> cookies) {
StringBuilder cookieHeader = new StringBuilder();
for (int i = 0, size = cookies.size(); i < size; i++) {
if (i > 0) {
cookieHeader.append("; ");
}
Cookie cookie = cookies.get(i);
cookieHeader.append(cookie.name()).append('=').append(cookie.value());
}
return cookieHeader.toString();
}
public void receiveHeaders(Headers headers) throws IOException {
if (client.cookieJar() == CookieJar.NO_COOKIES) return;
List<Cookie> cookies = Cookie.parseAll(userRequest.url(), headers);
if (cookies.isEmpty()) return;
client.cookieJar().saveFromResponse(userRequest.url(), cookies);
}
通過以上幾個關(guān)鍵方法恩溅,可以很明顯的感覺到作者的意圖了隔箍,為了更加自由定制化的cookie管理。其中loadForRequest()
脚乡、 saveFromResponse()
這兩個方法最為關(guān)鍵蜒滩,分別是在發(fā)送時向request header中加入cookie,在接收時奶稠,讀取response header中的
Cookies
持久化
對Cookies
持久化的方案俯艰,與之前版本并無很大區(qū)別,還是參考 android-async-http 這個庫锌订,主要參考其中兩個類:
-PersistentCookieStore
-
SerializableHttpCookie
與之前版本的區(qū)別是要將對java.net.HttpCookie
這個類的緩存處理換成對okhttp3.Cookie
的處理竹握,其他方面幾乎一樣。
廢話不多說了辆飘,直接上代碼
SerializableOkHttpCookies
主要做兩件事:將Cookie
對象輸出為ObjectStream
將ObjectStream
序列化成Cookie
對象
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();
}
}
PersistentCookieStore
根據(jù)一定的規(guī)則去緩存或者獲取Cookie
SharedPreferences
存儲
public class PersistentCookieStore {
private static final String LOG_TAG = "PersistentCookieStore";
private static final String COOKIE_PREFS = "Cookies_Prefs";
private final Map<String, ConcurrentHashMap<String, Cookie>> cookies;
private final SharedPreferences cookiePrefs;
public PersistentCookieStore(Context context) {
cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
cookies = new HashMap<>();
//將持久化的cookies緩存到內(nèi)存中 即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 decodedCookie = decodeCookie(encodedCookie);
if (decodedCookie != null) {
if (!cookies.containsKey(entry.getKey())) {
cookies.put(entry.getKey(), new ConcurrentHashMap<String, Cookie>());
}
cookies.get(entry.getKey()).put(name, decodedCookie);
}
}
}
}
}
protected String getCookieToken(Cookie cookie) {
return cookie.name() + "@" + cookie.domain();
}
public void add(HttpUrl url, Cookie cookie) {
String name = getCookieToken(cookie);
//將cookies緩存到內(nèi)存中 如果緩存過期 就重置此cookie
if (!cookie.persistent()) {
if (!cookies.containsKey(url.host())) {
cookies.put(url.host(), new ConcurrentHashMap<String, Cookie>());
}
cookies.get(url.host()).put(name, cookie);
} else {
if (cookies.containsKey(url.host())) {
cookies.get(url.host()).remove(name);
}
}
//講cookies持久化到本地
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));
prefsWriter.putString(name, encodeCookie(new SerializableOkHttpCookies(cookie)));
prefsWriter.apply();
}
public List<Cookie> get(HttpUrl url) {
ArrayList<Cookie> ret = new ArrayList<>();
if (cookies.containsKey(url.host()))
ret.addAll(cookies.get(url.host()).values());
return ret;
}
public boolean removeAll() {
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.clear();
prefsWriter.apply();
cookies.clear();
return true;
}
public boolean remove(HttpUrl url, Cookie cookie) {
String name = getCookieToken(cookie);
if (cookies.containsKey(url.host()) && cookies.get(url.host()).containsKey(name)) {
cookies.get(url.host()).remove(name);
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
if (cookiePrefs.contains(name)) {
prefsWriter.remove(name);
}
prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.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;
}
/**
* cookies 序列化成 string
*
* @param cookie 要序列化的cookie
* @return 序列化之后的string
*/
protected 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
*/
protected 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;
}
/**
* 二進制數(shù)組轉(zhuǎn)十六進制字符串
*
* @param bytes byte array to be converted
* @return string containing hex values
*/
protected 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);
}
/**
* 十六進制字符串轉(zhuǎn)二進制數(shù)組
*
* @param hexString string of hex-encoded values
* @return decoded byte array
*/
protected 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;
}
}
最終效果
完成對Cookie
持久化之后啦辐,就可以對Cookiejar
進行進一步修改了,最終效果:
/** * 自動管理Cookies */
private class CookiesManager implements CookieJar {
private final PersistentCookieStore cookieStore = new PersistentCookieStore(getApplicationContext());
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
if (cookies != null && cookies.size() > 0) {
for (Cookie item : cookies) {
cookieStore.add(url, item);
}
}
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = cookieStore.get(url);
return cookies;
}
}
最后設(shè)置OkHttpClient
OkHttpClient.Builder builder = new OkHttpClient.Builder();
Cookiebuilder.cookieJar(new CookiesManager());