注: 主要參考HTTP cookies 詳解,筆記作成思惟導圖javascript
RFC2965-HTTP State Management Mechanismhtml
根據構造能夠看出,基本是按照cookie規範來的java
private Cookie(String name, String value, long expiresAt, String domain, String path,
boolean secure, boolean httpOnly, boolean hostOnly, boolean persistent) {
this.name = name;
this.value = value;
this.expiresAt = expiresAt;//過時時間
this.domain = domain;//域
this.path = path;//子路徑匹配
this.secure = secure;//是否僅應用於https
this.httpOnly = httpOnly;//是否禁止javascript操做cookie
this.hostOnly = hostOnly;//是否針對特定主機
this.persistent = persistent;//是否持久化
}
Cookie(Builder builder) {
if (builder.name == null) throw new NullPointerException("builder.name == null");
if (builder.value == null) throw new NullPointerException("builder.value == null");
if (builder.domain == null) throw new NullPointerException("builder.domain == null");
this.name = builder.name;
this.value = builder.value;
this.expiresAt = builder.expiresAt;
this.domain = builder.domain;
this.path = builder.path;
this.secure = builder.secure;
this.httpOnly = builder.httpOnly;
this.persistent = builder.persistent;
this.hostOnly = builder.hostOnly;
}複製代碼
三,二,一,走git
List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
if (!cookies.isEmpty()) {
requestBuilder.header("Cookie", cookieHeader(cookies));
//給request設置cookie,List<Cookie> cookies由cookieJar.loadForRequest方法返回,該方式由開發者實現.
}
if (userRequest.header("User-Agent") == null) {
requestBuilder.header("User-Agent", Version.userAgent());
}
Response networkResponse = chain.proceed(requestBuilder.build());
HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
//從response中解析出cookies,字符串變成List<Cookie>,交給cookiejar接口處理
Response.Builder responseBuilder = networkResponse.newBuilder()
.request(userRequest);複製代碼
header中格式相似下面
Set-Cookie:name1=value1;name2=value2 ;expires=date;domain=domain ;path=path ;secure;httpOnly github
從response中拿到headers數組
從headers中拿到"Set-Cookie"對應的內容(String)瀏覽器
將拿到的String根據cookie字符串特色解析,並構建Cookie類緩存
public static void receiveHeaders(CookieJar cookieJar, HttpUrl url, Headers headers) {
if (cookieJar == CookieJar.NO_COOKIES) return;
List<Cookie> cookies = Cookie.parseAll(url, headers);//關鍵的解析方法在這裏面
if (cookies.isEmpty()) return;
cookieJar.saveFromResponse(url, cookies);//解析出的cookies交給cookieJar,讓它去決定怎麼保存
}複製代碼
public static List<Cookie> parseAll(HttpUrl url, Headers headers) {
List<String> cookieStrings = headers.values("Set-Cookie");//能夠解析headers中多個Set-Cookie字段
List<Cookie> cookies = null;
for (int i = 0, size = cookieStrings.size(); i < size; i++) {
Cookie cookie = Cookie.parse(url, cookieStrings.get(i));//Set-Cookie:後方的cookie內容的核心解析方法:
if (cookie == null) continue;
if (cookies == null) cookies = new ArrayList<>();
cookies.add(cookie);
}
return cookies != null
? Collections.unmodifiableList(cookies)
: Collections.<Cookie>emptyList();
}複製代碼
對照着cookie規範來看cookie
static Cookie parse(long currentTimeMillis, HttpUrl url, String setCookie) {
int pos = 0;
int limit = setCookie.length();
int cookiePairEnd = delimiterOffset(setCookie, pos, limit, ';');
int pairEqualsSign = delimiterOffset(setCookie, pos, cookiePairEnd, '=');
if (pairEqualsSign == cookiePairEnd) return null;
String cookieName = trimSubstring(setCookie, pos, pairEqualsSign);//拿到name
if (cookieName.isEmpty() || indexOfControlOrNonAscii(cookieName) != -1) return null;
String cookieValue = trimSubstring(setCookie, pairEqualsSign + 1, cookiePairEnd);//拿到value
if (indexOfControlOrNonAscii(cookieValue) != -1) return null;
long expiresAt = HttpDate.MAX_DATE;//默認有效期很長
long deltaSeconds = -1L;
String domain = null;
String path = null;
boolean secureOnly = false;
boolean httpOnly = false;
boolean hostOnly = true;
boolean persistent = false;//默認爲會話cookie
//解析name=value;後面的幾個屬性
pos = cookiePairEnd + 1;
while (pos < limit) {
int attributePairEnd = delimiterOffset(setCookie, pos, limit, ';');//拿到後一個分號的
int attributeEqualsSign = delimiterOffset(setCookie, pos, attributePairEnd, '=');
String attributeName = trimSubstring(setCookie, pos, attributeEqualsSign);//拿到屬性名
//拿到屬性值
String attributeValue = attributeEqualsSign < attributePairEnd
? trimSubstring(setCookie, attributeEqualsSign + 1, attributePairEnd)
: "";
//一個個匹配並賦值
if (attributeName.equalsIgnoreCase("expires")) {
try {
expiresAt = parseExpires(attributeValue, 0, attributeValue.length());
persistent = true;
} catch (IllegalArgumentException e) {
// Ignore this attribute, it isn't recognizable as a date.
}
} else if (attributeName.equalsIgnoreCase("max-age")) {
try {
deltaSeconds = parseMaxAge(attributeValue);
persistent = true;
} catch (NumberFormatException e) {
// Ignore this attribute, it isn't recognizable as a max age.
}
} else if (attributeName.equalsIgnoreCase("domain")) {
try {
domain = parseDomain(attributeValue);
hostOnly = false;
} catch (IllegalArgumentException e) {
// Ignore this attribute, it isn't recognizable as a domain.
}
} else if (attributeName.equalsIgnoreCase("path")) {
path = attributeValue;
} else if (attributeName.equalsIgnoreCase("secure")) {
secureOnly = true;
} else if (attributeName.equalsIgnoreCase("httponly")) {
httpOnly = true;
}
pos = attributePairEnd + 1;
}
//拿過時時間
// If 'Max-Age' is present, it takes precedence over 'Expires', regardless of the order the two
// attributes are declared in the cookie string.
if (deltaSeconds == Long.MIN_VALUE) {
expiresAt = Long.MIN_VALUE;
} else if (deltaSeconds != -1L) {
long deltaMilliseconds = deltaSeconds <= (Long.MAX_VALUE / 1000)
? deltaSeconds * 1000
: Long.MAX_VALUE;
expiresAt = currentTimeMillis + deltaMilliseconds;
if (expiresAt < currentTimeMillis || expiresAt > HttpDate.MAX_DATE) {
expiresAt = HttpDate.MAX_DATE; // Handle overflow & limit the date range.
}
}
// If the domain is present, it must domain match. Otherwise we have a host-only cookie.
if (domain == null) {
domain = url.host();//有規定domain,就按domain的規則,沒有,就嚴格匹配host
} else if (!domainMatch(url, domain)) {//域不匹配,set cookie無效,棄之
return null; // No domain match? This is either incompetence or malice!
}
// If the path is absent or didn't start with '/', use the default path. It's a string like
// '/foo/bar' for a URL like 'http://example.com/foo/bar/baz'. It always starts with '/'.
if (path == null || !path.startsWith("/")) {
String encodedPath = url.encodedPath();
int lastSlash = encodedPath.lastIndexOf('/');
path = lastSlash != 0 ? encodedPath.substring(0, lastSlash) : "/";
}
return new Cookie(cookieName, cookieValue, expiresAt, domain, path, secureOnly, httpOnly,
hostOnly, persistent);
}複製代碼
cookieJar.saveFromResponse(url, cookies);複製代碼
追蹤源碼能夠看到,cookieJar是由OkHttpClient傳遞過來的,是由OkHttpClient.Builder.cookieJar(cookieJar)傳進來,具體由用戶實現.OkHttpClient.Builder提供了默認實現:網絡
cookieJar = CookieJar.NO_COOKIES;複製代碼
其實現爲:
public interface CookieJar {
/** A cookie jar that never accepts any cookies. */
CookieJar NO_COOKIES = new CookieJar() {
@Override public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
}
@Override public List<Cookie> loadForRequest(HttpUrl url) {
return Collections.emptyList();
}
};
void saveFromResponse(HttpUrl url, List<Cookie> cookies);
List<Cookie> loadForRequest(HttpUrl url);
}複製代碼
很是簡單了,就是CookieJar接口的loadForRequest方法,默認是返回null,若是管理,須要用戶本身實現
BridgeInterceptor的intercept方法中
List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
if (!cookies.isEmpty()) {
requestBuilder.header("Cookie", cookieHeader(cookies));
//給request設置cookie,List<Cookie> cookies由cookieJar.loadForRequest方法返回,該方式由開發者實現.
}複製代碼
從上面的源碼分析能夠看出,cookie管理中,cookie解析和cookie設置兩個部分都不用咱們操心,框架幫咱們作了,咱們要作的是實現cookieJar來定製cookie的保存.
咱們很容易就能夠知道,有三種狀況
okhttp已經內置了,就是CookieJar.NO_COOKIES
new CookieJar() {
private final HashMap<String, List<Cookie>> cookieStore = new HashMap<String, List<Cookie>>();
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
cookieStore.put(url.host(), cookies);
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = cookieStore.get(url.host());
return cookies != null ? cookies : new ArrayList<Cookie>();
}
})複製代碼
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;
}
}複製代碼
用SharedPreferences來保存
注: 參考OkHttp3實現Cookies管理及持久化
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緩存到內存中 即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緩存到內存中 若是緩存過時 就重置此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;
}
/** * 二進制數組轉十六進制字符串 * * @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);
}
/** * 十六進制字符串轉二進制數組 * * @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;
}
}複製代碼
既然List
是我返回給框架的,那麼我能夠改動,或者手動添加一個全新的cookie,這個就不展開了.
okhttp對cookie的實現中,作了兩件事:
按照規範把response header中的"set-cookie"字段解析成List
把cookieJar返回的List
須要用戶作的事是定義cookie的保存方式:
是不保存,仍是保存在內存,仍是持久化到硬盤,方式是經過實現CookieJar接口