OkHttp 內(nèi)置了 5 個攔截器,在每一個攔截器里,分別對請求信息和響應(yīng)值做了處理,每一層只做當(dāng)前相關(guān)的操作,這五個攔截器分別是:
RetryAndFollowUpInterceptor,BridgeInterceptor,CacheInterceptor,ConnectInterceptor,CallServerInterceptor.
他們的作用分別如下:
- RetryAndFollowUpInterceptor:取消、失敗重試、重定向
- BridgeInterceptor:把用戶請求轉(zhuǎn)換為 HTTP 請求;把 HTTP 響應(yīng)轉(zhuǎn)換為用戶友好的響應(yīng)
- CacheInterceptor:讀寫緩存、根據(jù)策略決定是否使用
- ConnectInterceptor:和服務(wù)器建立連接
- CallServerInterceptor:實現(xiàn)讀寫數(shù)據(jù)
RetryAndFollowUpInterceptor
通過前面對OkHttp攔截器攔截過程的學(xué)習(xí),我們知道,在請求的時候,RetryAndFollowUpInterceptor是第一個會被調(diào)用的內(nèi)置攔截器,攔截器的核心邏輯就在攔截方法:
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Call call = realChain.call();
EventListener eventListener = realChain.eventListener();
//注意:新創(chuàng)建了一個流分配管理類對象,這個類很重要
StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
createAddress(request.url()), call, eventListener, callStackTrace);
this.streamAllocation = streamAllocation;
int followUpCount = 0; //重定向次數(shù)
Response priorResponse = null;
while (true) { //while循環(huán)
if (canceled) { //檢查當(dāng)前請求是否被取消,如果這時請求被取消了,則會通StreamAllocation釋放連接
streamAllocation.release();
throw new IOException("Canceled");
}
Response response;
boolean releaseConnection = true;
try {
response = realChain.proceed(request, streamAllocation, null, null);
releaseConnection = false; //請求過程中,只要發(fā)生未處理的異常,releaseConnection 就會 為true,一旦變?yōu)閠rue,就會將StreamAllocation釋放掉
} catch (RouteException e) {
// The attempt to connect via a route failed. The request will not have been sent.
if (!recover(e.getLastConnectException(), streamAllocation, false, request)) {
throw e.getLastConnectException();
}
releaseConnection = false;
continue; //發(fā)生異常就繼續(xù)循環(huán)
} catch (IOException e) {
// An attempt to communicate with a server failed. The request may have been sent.
boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
if (!recover(e, streamAllocation, requestSendStarted, request)) throw e;
releaseConnection = false;
continue; //繼續(xù)循環(huán)
} finally {
// We're throwing an unchecked exception. Release any resources.
if (releaseConnection) { //releaseConnection一旦為true,就釋放連接
streamAllocation.streamFailed(null);
streamAllocation.release();
}
}
// Attach the prior response if it exists. Such responses never have a body.
if (priorResponse != null) {
response = response.newBuilder()
.priorResponse(priorResponse.newBuilder()
.body(null)
.build())
.build();
}
//根據(jù) code 和 method 判斷是否需要重定向請求
Request followUp = followUpRequest(response, streamAllocation.route());
if (followUp == null) { //不需要重定向時直接返回結(jié)果
if (!forWebSocket) {
streamAllocation.release();
}
return response;
}
closeQuietly(response.body());
//重定向次數(shù)先+1,然后判斷是否大于重定向次數(shù)的最大值20
if (++followUpCount > MAX_FOLLOW_UPS) {
streamAllocation.release();
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}
if (followUp.body() instanceof UnrepeatableRequestBody) {
streamAllocation.release();
throw new HttpRetryException("Cannot retry streamed HTTP body", response.code());
}
//是否可以復(fù)用當(dāng)前連接,如果不能,則釋放當(dāng)前連接,重新建立連接
if (!sameConnection(response, followUp.url())) {
streamAllocation.release();
streamAllocation = new StreamAllocation(client.connectionPool(),
createAddress(followUp.url()), call, eventListener, callStackTrace);
this.streamAllocation = streamAllocation;
} else if (streamAllocation.codec() != null) {
throw new IllegalStateException("Closing the body of " + response
+ " didn't close its backing stream. Bad interceptor?");
}
request = followUp;
priorResponse = response;
}
}
可以看到RetryAndFollowUpInterceptor的攔截操作:
- 新建了一個流引用分配管理類 StreamAllocation對象,也就是說,每一次請求都會新建一個StreamAllocation,因為
RetryAndFollowUpInterceptor是第一個攔截器- 然后在一個 while 循環(huán)中調(diào)用攔截器鏈的 proceed() 方法,執(zhí)行下一個攔截器
- 拿到響應(yīng)的過程中如果出現(xiàn)路由異常、IO 異常,就 continue 請求(即失敗重試)
- 根據(jù)拿到的響應(yīng)結(jié)果, 在
followUpRequest()方法中判斷是否需要重定向,如果不需要直接返回響應(yīng)結(jié)果- 如果需要重定向,先判斷重定向次數(shù)是否超過最大值,在判斷重定向請求是否可以復(fù)用當(dāng)前連接,如果不可以,則要釋放當(dāng)前連接并新建
- 重新設(shè)置request,并將當(dāng)前響應(yīng)賦值給priorResponse ,繼續(xù)while循環(huán)
那么okhttp是怎么判斷需要重定向的呢,看下followUpRequest()
private Request followUpRequest(Response userResponse, Route route) throws IOException {
if (userResponse == null) throw new IllegalStateException();
//響應(yīng)狀態(tài)碼
int responseCode = userResponse.code();
//請求method
final String method = userResponse.request().method();
switch (responseCode) {
case HTTP_PROXY_AUTH: //407代理服務(wù)器驗證
Proxy selectedProxy = route != null
? route.proxy()
: client.proxy();
if (selectedProxy.type() != Proxy.Type.HTTP) {
throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy");
}
return client.proxyAuthenticator().authenticate(route, userResponse);
case HTTP_UNAUTHORIZED: //401,未驗證
return client.authenticator().authenticate(route, userResponse);
case HTTP_PERM_REDIRECT: //308
case HTTP_TEMP_REDIRECT: //307
// "If the 307 or 308 status code is received in response to a request other than GET
// or HEAD, the user agent MUST NOT automatically redirect the request"
if (!method.equals("GET") && !method.equals("HEAD")) {
return null;
}
// fall-through
case HTTP_MULT_CHOICE: //300
case HTTP_MOVED_PERM: //301
case HTTP_MOVED_TEMP: //302
case HTTP_SEE_OTHER: //303
// Does the client allow redirects?
//okHttpClient不允許重定向,返回null
if (!client.followRedirects()) return null;
String location = userResponse.header("Location");
if (location == null) return null;
//根據(jù)location拿到要重定向的url
HttpUrl url = userResponse.request().url().resolve(location);
// Don't follow redirects to unsupported protocols.
if (url == null) return null;
// If configured, don't follow redirects between SSL and non-SSL.
boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());
//如果url不同,并且不允許ssl重定向,返回null
if (!sameScheme && !client.followSslRedirects()) return null;
// Most redirects don't include a request body.
Request.Builder requestBuilder = userResponse.request().newBuilder();
if (HttpMethod.permitsRequestBody(method)) {
final boolean maintainBody = HttpMethod.redirectsWithBody(method);
if (HttpMethod.redirectsToGet(method)) {
requestBuilder.method("GET", null);
} else {
RequestBody requestBody = maintainBody ? userResponse.request().body() : null;
requestBuilder.method(method, requestBody);
}
if (!maintainBody) {
requestBuilder.removeHeader("Transfer-Encoding");
requestBuilder.removeHeader("Content-Length");
requestBuilder.removeHeader("Content-Type");
}
}
// When redirecting across hosts, drop all authentication headers. This
// is potentially annoying to the application layer since they have no
// way to retain them.
if (!sameConnection(userResponse, url)) {
requestBuilder.removeHeader("Authorization");
}
return requestBuilder.url(url).build();
case HTTP_CLIENT_TIMEOUT: //408
// 408's are rare in practice, but some servers like HAProxy use this response code. The
// spec says that we may repeat the request without modifications. Modern browsers also
// repeat the request (even non-idempotent ones.)
if (!client.retryOnConnectionFailure()) {
// The application layer has directed us not to retry the request.
return null;
}
if (userResponse.request().body() instanceof UnrepeatableRequestBody) {
return null;
}
//前一次響應(yīng)也超時,就放棄重定向,返回null
if (userResponse.priorResponse() != null
&& userResponse.priorResponse().code() == HTTP_CLIENT_TIMEOUT) {
// We attempted to retry and got another timeout. Give up.
return null;
}
if (retryAfter(userResponse, 0) > 0) {
return null;
}
return userResponse.request();
case HTTP_UNAVAILABLE: //503
//上一次響應(yīng)狀態(tài)也是503,返回null
if (userResponse.priorResponse() != null
&& userResponse.priorResponse().code() == HTTP_UNAVAILABLE) {
// We attempted to retry and got another timeout. Give up.
return null;
}
//如果響應(yīng)頭Retry-After要求立即重試,就重新請求
if (retryAfter(userResponse, Integer.MAX_VALUE) == 0) {
// specifically received an instruction to retry without delay
return userResponse.request();
}
return null;
default:
return null;
}
}
可以看到重定向的判斷依據(jù)就是是狀態(tài)碼和請求方法,總結(jié)一下這里的判斷邏輯
- 狀態(tài)碼是407,先判斷代理服務(wù)器的類型,如果不是HTTP代理就拋異常。如果是,會調(diào)用我們構(gòu)造 OkHttpClient 時傳入的 Authenticator,做鑒權(quán)處理操作,返回處理后的結(jié)果
- 狀態(tài)碼是401,和407一樣,做認(rèn)證操作,然后返回結(jié)果
- 狀態(tài)碼是308或者307重定向,且方法不是 GET 也不是 HEAD,就返回 null
- 狀態(tài)碼 是 300、301、302、303,且構(gòu)造 OkHttpClient 時設(shè)置允許重定向,就從當(dāng)前響應(yīng)頭中取出 Location 即新地址,然后構(gòu)造一個新的 Request 再請求一次
- 狀態(tài)碼 是 408 超時,且上一次沒有超時,就再請求一次
- 狀態(tài)碼 是 503 服務(wù)不可用,且上一次不是 503,響應(yīng)頭也要求立即重試,就重新請求一次
所以followUpRequest()的返回值不為null,就表示需要重定向,為null,表示不需要.
BridgeInterceptor
BridgeInterceptor主要負(fù)責(zé)對Request和Response報文進(jìn)行加工,將用戶構(gòu)造的請求轉(zhuǎn)換為發(fā)送到服務(wù)器的請求、把服務(wù)器返回的響應(yīng)轉(zhuǎn)換為用戶友好的響應(yīng),直接看它的攔截方法:
@Override
public Response intercept(Chain chain) throws IOException {
Request userRequest = chain.request();
Request.Builder requestBuilder = userRequest.newBuilder();
RequestBody body = userRequest.body();
//以下是根據(jù)請求體,補全請求頭
if (body != null) {
MediaType contentType = body.contentType();
if (contentType != null) {
requestBuilder.header("Content-Type", contentType.toString());
}
long contentLength = body.contentLength();
if (contentLength != -1) {
requestBuilder.header("Content-Length", Long.toString(contentLength));
requestBuilder.removeHeader("Transfer-Encoding");
} else {
requestBuilder.header("Transfer-Encoding", "chunked");
requestBuilder.removeHeader("Content-Length");
}
}
if (userRequest.header("Host") == null) {
requestBuilder.header("Host", hostHeader(userRequest.url(), false));
}
if (userRequest.header("Connection") == null) {
requestBuilder.header("Connection", "Keep-Alive");
}
// If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing
// the transfer stream.
boolean transparentGzip = false;
if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
transparentGzip = true;
requestBuilder.header("Accept-Encoding", "gzip");
}
//加載cookie,cookieJar是在創(chuàng)建okhttpClient配置的,不配置就用默認(rèn)的
List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
if (!cookies.isEmpty()) {
//將本地的cookie拼接成字符串,并設(shè)置給Cookie頭
requestBuilder.header("Cookie", cookieHeader(cookies));
}
if (userRequest.header("User-Agent") == null) {
requestBuilder.header("User-Agent", Version.userAgent());
}
Response networkResponse = chain.proceed(requestBuilder.build());
//以下是對響應(yīng)頭的處理
//解析并保存服務(wù)器返回的cookie,如果沒有自定義cookie,不會解析
HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
Response.Builder responseBuilder = networkResponse.newBuilder()
.request(userRequest);
//如果響應(yīng)內(nèi)容是以gzip壓縮過,就解壓
if (transparentGzip
&& "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))
&& HttpHeaders.hasBody(networkResponse)) {
GzipSource responseBody = new GzipSource(networkResponse.body().source());
//移除響應(yīng)頭Content-Encoding和Content-Length
Headers strippedHeaders = networkResponse.headers().newBuilder()
.removeAll("Content-Encoding")
.removeAll("Content-Length")
.build();
//構(gòu)建一個新的響應(yīng)
responseBuilder.headers(strippedHeaders);
String contentType = networkResponse.header("Content-Type");
responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
}
//將新的響應(yīng)返回
return responseBuilder.build();
}
BridgeInterceptor做的主要工作是:
- 在發(fā)送請求前,根據(jù)body補全請求頭,補全的請求頭:Content-Type、Content-Length、Transfer-Encoding、Host、Connection、Cookie、Accept-Encoding、User-Agent
- 創(chuàng)建新的請求,執(zhí)行下一個攔截器
- 如果響應(yīng)內(nèi)容以gzip壓縮過,先解壓,移除響應(yīng)頭Content-Encoding和Content-Length,再構(gòu)建一個新的response返回
- 沒有壓縮過,直接返回response
CacheInterceptor
CacheInterceptor是根據(jù)HTTP協(xié)議的緩存機制來做緩存處理的,所以有必要先了解一下HTTP協(xié)議的緩存機制.
HTTP協(xié)議中緩存相關(guān)
緩存分類
http請求有服務(wù)端和客戶端之分。因此緩存也可以分為兩個類型服務(wù)端側(cè)和客戶端側(cè)。
服務(wù)端側(cè)緩存
常見的服務(wù)端有Ngix和Apache。服務(wù)端緩存又分為代理服務(wù)器緩存和反向代理服務(wù)器緩存。常見
的CDN就是服務(wù)器緩存。這個好理解,當(dāng)瀏覽器重復(fù)訪問一張圖片地址時,CDN會判斷這個請求
有沒有緩存,如果有的話就直接返回這個緩存的請求回復(fù),而不再需要讓請求到達(dá)真正的服務(wù)地
址,這么做的目的是減輕服務(wù)端的運算壓力。
客戶端側(cè)緩存
客戶端主要指瀏覽器(如IE、Chrome等),當(dāng)然包括我們的OKHTTPClient.客戶端第一次請求網(wǎng)
絡(luò)時,服務(wù)器返回回復(fù)信息。如果數(shù)據(jù)正常的話,客戶端緩存在本地的緩存目錄。當(dāng)客戶端再次
訪問同一個地址時,客戶端會檢測本地有沒有緩存,如果有緩存的話,數(shù)據(jù)是有沒有過期,如果
沒有過期的話則直接運用緩存內(nèi)容。
HTTP 緩存策略
在 HTTP 協(xié)議中,定義了一些與緩存相關(guān)的Header:
Cache-Control
Etag, If-None_match
LastModified, If-Modified-Since
Expired
Cache-Control
Cache-control 是HTTP協(xié)議中一個用來控制緩存的頭部字段,既可以在請求頭中使用,也可以在響應(yīng)頭中使用。它有不同的值,不同的值代表不同的緩存策略
Cache-control在請求頭中使用的值有:
no-cache: 不使用緩存的數(shù)據(jù),直接從服務(wù)器去取
only-if-cached: 表示直接獲取緩存數(shù)據(jù),若沒有數(shù)據(jù)返回,則返回504(Gateway Timeout)
max-age: 表示可接受過期多久的緩存數(shù)據(jù)
max-stale:已過期的緩存在多少時間內(nèi)仍可以繼續(xù)使用(類似保質(zhì)期),可以接受過去的對象,但是過期時間必須小于 max-stale 值
min-fresh:表示指定時間內(nèi)的緩存數(shù)據(jù)仍有效,與緩存是否過期無關(guān)。如min-fresh: 60, 表示60s內(nèi)的緩存數(shù)據(jù)都有效,60s之后的緩存數(shù)據(jù)將無效。
Cache-control在響應(yīng)頭中使用的值有:
public:可向任一方提供緩存數(shù)據(jù)
private:只向指定用戶提供緩存數(shù)據(jù)
no-cache:緩存服務(wù)器不能對資源進(jìn)行緩存
no-store:不緩存請求或響應(yīng)的任何內(nèi)容
max-age: 表示緩存的最大時間,在此時間范圍內(nèi),訪問該資源時,直接返回緩存數(shù)據(jù)。不需要對資源的有效性進(jìn)行確認(rèn);
Etag/If-None-Match
Etag:服務(wù)器響應(yīng)請求時,告訴客戶端當(dāng)前資源在服務(wù)器的唯一標(biāo)識(生成規(guī)則由服務(wù)器決定)
If-None-Match: 如果瀏覽器在Cache-Control:max-age=60設(shè)置的時間超時后,發(fā)現(xiàn)消息頭中還設(shè)
置了Etag值。然后,瀏覽器會再次向服務(wù)器請求數(shù)據(jù)并添加If-None-Match消息頭,它的值就是之
前Etag值。再次請求服務(wù)器時,客戶端通過此字段通知服務(wù)器客戶端緩存數(shù)據(jù)的唯一標(biāo)識。服務(wù)
器收到請求后發(fā)現(xiàn)有頭部If-None-Match,則與被請求的資源的唯一標(biāo)識進(jìn)行對比,不同則說明源
被改過,則響應(yīng)整個內(nèi)容,返回狀態(tài)碼是200,相同則說明資源沒有被改動過,則響應(yīng)狀態(tài)碼
304,告知客戶端可以使用緩存
LastModified, If-Modified-Since
Last-Modified:標(biāo)示這個響應(yīng)資源的最后修改時間。web服務(wù)器在響應(yīng)請求時,告訴瀏覽器資源的
最后修改時間。
If-Modified-Since:當(dāng)資源過期時(使用Cache-Control標(biāo)識的max-age),發(fā)現(xiàn)資源具有Last-
Modified聲明,則再次向web服務(wù)器請求時帶上頭 If-Modified-Since,表示請求時間。web服務(wù)器
收到請求后發(fā)現(xiàn)有頭If-Modified-Since 則與被請求資源的最后修改時間進(jìn)行比對。若最后修改時間
較新,說明資源又被改動過,則響應(yīng)整片資源內(nèi)容(寫在響應(yīng)消息包體內(nèi)),HTTP 200;若最后
修改時間較舊,說明資源無需修改,則響應(yīng)HTTP 304 (無需包體,節(jié)省瀏覽),告知瀏覽器繼續(xù)使
用所保存的cache。
Expired
expires的效果等同于Cache-Control,不過它是Http 1.0的內(nèi)容,它的作用是告訴瀏覽器緩存的過
期時間,在此時間內(nèi)瀏覽器不需要直接訪問服務(wù)器地址直接用緩存內(nèi)容就好了。
expires最大的問題在于如果服務(wù)器時間和本地瀏覽器相差過大的問題。那樣誤差就很大。所以基
本上用Cache-Control:max-age=多少秒的形式代替。
用一張圖來表示HTTP的緩存機制就是:

概括起來就是:
- 首先根據(jù) CacheControl 來判斷是否使用緩存,如果使用緩存,就去判斷當(dāng)前緩存是否過期
- 如果緩存信息里有 Etag,就向服務(wù)器發(fā)送帶 If-None-Match 的請求,服務(wù)器進(jìn)行決策
- 如果沒有 Etag 就看有沒有 Last-Modified,有的話向服務(wù)器發(fā)送帶 If-Modified-Since 的請求, 由服務(wù)器進(jìn)行決策
- 服務(wù)器驗證緩存有效性后,如果緩存仍可以使用,就返回 304;如果 code 不是 304,客戶端就需要從響應(yīng)里拿數(shù)據(jù),同時更新緩存。
OkHttp的緩存攔截器實現(xiàn)
public final class CacheInterceptor implements Interceptor {
final InternalCache cache;
public CacheInterceptor(InternalCache cache) {
this.cache = cache;
}
@Override
public Response intercept(Chain chain) throws IOException {
//如果有緩存,取出緩存,cache是在OkHttpClient中設(shè)置的,如果不設(shè)置就為null
Response cacheCandidate = cache != null
? cache.get(chain.request())
: null;
long now = System.currentTimeMillis();
//獲取緩存策略對象
CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
//從緩存策略中拿到networkRequest ,networkRequest 不為null,表示要請求網(wǎng)絡(luò)
Request networkRequest = strategy.networkRequest;
//緩存策略中拿到cacheResponse ,cacheResponse 不為null,表示緩存可用
Response cacheResponse = strategy.cacheResponse;
....
}
首先是判斷cache是否為null,如果不為null,就調(diào)用cache.get(chain.request())取出緩存響應(yīng),看一下這個cache:
public interface InternalCache {
Response get(Request request) throws IOException;
CacheRequest put(Response response) throws IOException;
void remove(Request request) throws IOException;
void update(Response cached, Response network);
void trackConditionalCacheHit();
void trackResponse(CacheStrategy cacheStrategy);
}
cache是InternalCache類型的接口,它唯一的實現(xiàn)在Cache類:
public final class Cache implements Closeable, Flushable {
private static final int VERSION = 201105;
private static final int ENTRY_METADATA = 0;
private static final int ENTRY_BODY = 1;
private static final int ENTRY_COUNT = 2;
//創(chuàng)建一個InternalCache 成員
final InternalCache internalCache = new InternalCache() {
@Override public Response get(Request request) throws IOException {
//InternalCache的get方法其實調(diào)用的是Cache的get方法
return Cache.this.get(request);
}
.......
};
final DiskLruCache cache;
...........
public Cache(File directory, long maxSize) {
this(directory, maxSize, FileSystem.SYSTEM);
}
Cache(File directory, long maxSize, FileSystem fileSystem) {
this.cache = DiskLruCache.create(fileSystem, directory, VERSION, ENTRY_COUNT, maxSize);
}
public static String key(HttpUrl url) { //緩存的key值就是對url進(jìn)行utf-8轉(zhuǎn)碼,并取md5
return ByteString.encodeUtf8(url.toString()).md5().hex();
}
@Nullable Response get(Request request) {
String key = key(request.url());
DiskLruCache.Snapshot snapshot;
Entry entry;
try {
snapshot = cache.get(key);
if (snapshot == null) {
return null;
}
} catch (IOException e) {
// Give up because the cache cannot be read.
return null;
}
try {
entry = new Entry(snapshot.getSource(ENTRY_METADATA));
} catch (IOException e) {
Util.closeQuietly(snapshot);
return null;
}
Response response = entry.response(snapshot);
if (!entry.matches(request, response)) {
Util.closeQuietly(response.body());
return null;
}
return response;
}
..........
}
從Cache類可以看到OkHttp的緩存是用DiskLruCache 來存儲的,存儲的key就是請求的url的md5值.
繼續(xù)回到CacheInterceptor的攔截方法,在攔截方法中:
//構(gòu)建一個緩存策略對象
CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(),
cacheCandidate).get();
//從緩存策略對象中拿到networkRequest
Request networkRequest = strategy.networkRequest;
//緩存策略對象中拿到cacheResponse
Response cacheResponse = strategy.cacheResponse;
調(diào)用了CacheStrategy的Factory()和get():
public final class CacheStrategy {
public final @Nullable Request networkRequest;
public final @Nullable Response cacheResponse;
CacheStrategy(Request networkRequest, Response cacheResponse) {
this.networkRequest = networkRequest;
this.cacheResponse = cacheResponse;
}
.......
public static class Factory {
public Factory(long nowMillis, Request request, Response cacheResponse) {
this.nowMillis = nowMillis;
this.request = request;
this.cacheResponse = cacheResponse;
if (cacheResponse != null) {
this.sentRequestMillis = cacheResponse.sentRequestAtMillis();
this.receivedResponseMillis = cacheResponse.receivedResponseAtMillis();
Headers headers = cacheResponse.headers();
//獲取緩存響應(yīng)的header值
for (int i = 0, size = headers.size(); i < size; i++) {
String fieldName = headers.name(i);
String value = headers.value(i);
if ("Date".equalsIgnoreCase(fieldName)) {
servedDate = HttpDate.parse(value);
servedDateString = value;
} else if ("Expires".equalsIgnoreCase(fieldName)) {
expires = HttpDate.parse(value);
} else if ("Last-Modified".equalsIgnoreCase(fieldName)) {
lastModified = HttpDate.parse(value);
lastModifiedString = value;
} else if ("ETag".equalsIgnoreCase(fieldName)) {
etag = value;
} else if ("Age".equalsIgnoreCase(fieldName)) {
ageSeconds = HttpHeaders.parseSeconds(value, -1);
}
}
}
}
public CacheStrategy get() {
//獲取當(dāng)前的緩存策略
CacheStrategy candidate = getCandidate();
//如果是網(wǎng)絡(luò)請求不為null并且請求里面的cacheControl是只用緩存
if (candidate.networkRequest != null && request.cacheControl().onlyIfCached()) {
// We're forbidden from using the network and the cache is insufficient.
return new CacheStrategy(null, null);
}
return candidate;
}
/** Returns a strategy to use assuming the request can use the network. */
private CacheStrategy getCandidate() {
// No cached response.
if (cacheResponse == null) { //如果沒有緩存響應(yīng),返回一個沒有響應(yīng)的策略
return new CacheStrategy(request, null);
}
// Drop the cached response if it's missing a required handshake.
if (request.isHttps() && cacheResponse.handshake() == null) { //如果是https請求,并且握手丟失
return new CacheStrategy(request, null);
}
// If this response shouldn't have been stored, it should never be used
// as a response source. This check should be redundant as long as the
// persistence store is well-behaved and the rules are constant.
if (!isCacheable(cacheResponse, request)) { //如果響應(yīng)不能緩存(根據(jù)響應(yīng)狀態(tài)碼,請求或響應(yīng)頭的Cache-control字段判斷)
return new CacheStrategy(request, null);
}
CacheControl requestCaching = request.cacheControl();
//請求cacheControl設(shè)置為不緩存,或者請求頭里面有If-Modified-Since或If-None-Match頭部字段
if (requestCaching.noCache() || hasConditions(request)) {
return new CacheStrategy(request, null);
}
CacheControl responseCaching = cacheResponse.cacheControl();
//如果cache-Control的值是immutable
if (responseCaching.immutable()) {
return new CacheStrategy(null, cacheResponse);
}
//獲取緩存響應(yīng)的年齡
long ageMillis = cacheResponseAge();
//獲取緩存響應(yīng)的過期時間
long freshMillis = computeFreshnessLifetime();
//如果請求cache-control里面有過期時間max-age,則比較請求和響應(yīng)的過期時間,取最小值
if (requestCaching.maxAgeSeconds() != -1) {
freshMillis = Math.min(freshMillis, SECONDS.toMillis(requestCaching.maxAgeSeconds()));
}
long minFreshMillis = 0;
if (requestCaching.minFreshSeconds() != -1) {
minFreshMillis = SECONDS.toMillis(requestCaching.minFreshSeconds());
}
long maxStaleMillis = 0;
if (!responseCaching.mustRevalidate() && requestCaching.maxStaleSeconds() != -1) {
maxStaleMillis = SECONDS.toMillis(requestCaching.maxStaleSeconds());
}
if (!responseCaching.noCache() && ageMillis + minFreshMillis < freshMillis + maxStaleMillis) {
Response.Builder builder = cacheResponse.newBuilder();
if (ageMillis + minFreshMillis >= freshMillis) {
builder.addHeader("Warning", "110 HttpURLConnection \"Response is stale\"");
}
long oneDayMillis = 24 * 60 * 60 * 1000L;
if (ageMillis > oneDayMillis && isFreshnessLifetimeHeuristic()) {
builder.addHeader("Warning", "113 HttpURLConnection \"Heuristic expiration\"");
}
return new CacheStrategy(null, builder.build());
}
// Find a condition to add to the request. If the condition is satisfied, the response body
// will not be transmitted.
String conditionName;
String conditionValue;
if (etag != null) {
conditionName = "If-None-Match";
conditionValue = etag;
} else if (lastModified != null) {
conditionName = "If-Modified-Since";
conditionValue = lastModifiedString;
} else if (servedDate != null) {
conditionName = "If-Modified-Since";
conditionValue = servedDateString;
} else {
return new CacheStrategy(request, null); // No condition! Make a regular request.
}
Headers.Builder conditionalRequestHeaders = request.headers().newBuilder();
Internal.instance.addLenient(conditionalRequestHeaders, conditionName, conditionValue);
Request conditionalRequest = request.newBuilder()
.headers(conditionalRequestHeaders.build())
.build();
return new CacheStrategy(conditionalRequest, cacheResponse);
}
.......
}
可以看到CacheStrategy內(nèi)部的networkRequest和cacheResponse是通過HTTP協(xié)議緩存機制,也就是根據(jù)用戶對當(dāng)前請求設(shè)置的 CacheControl 的值,緩存響應(yīng)的時間、ETag 、 LastModified 或者 ServedDate 等 Header的值 進(jìn)行不斷的判斷得出來的.拿到兩個值之后,緩存攔截器CacheInterceptor 就根據(jù)這兩個值的情況決定是請求網(wǎng)絡(luò)還是直接返回緩存數(shù)據(jù)
@Override
public Response intercept(Chain chain) throws IOException {
Response cacheCandidate = cache != null
? cache.get(chain.request())
: null;
long now = System.currentTimeMillis();
CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(),cacheCandidate).get();
Request networkRequest = strategy.networkRequest;
Response cacheResponse = strategy.cacheResponse;
//緩存是否不為null(okhttpClient.builder可以設(shè)置,不設(shè)置默認(rèn)就為null)
if (cache != null) {
cache.trackResponse(strategy);
}
//有緩存,但是緩存不可用,
if (cacheCandidate != null && cacheResponse == null) {
closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
}
//networkRequest和cacheResponse都為null,表示禁止使用網(wǎng)絡(luò)請求,但是緩存又不可用,返回504錯誤
// If we're forbidden from using the network and the cache is insufficient, fail.
if (networkRequest == null && cacheResponse == null) {
return new Response.Builder()
.request(chain.request())
.protocol(Protocol.HTTP_1_1)
.code(504)
.message("Unsatisfiable Request (only-if-cached)")
.body(Util.EMPTY_RESPONSE)
.sentRequestAtMillis(-1L)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
}
//networkRequest為null,cacheResponse不為null,表示不使用網(wǎng)絡(luò)請求,并且緩存有效,直接返回緩存
// If we don't need the network, we're done.
if (networkRequest == null) {
return cacheResponse.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.build();
}
Response networkResponse = null;
try {
//networkRequest 不為null,就走到這里(networkRequest 不為null,表示需要請求網(wǎng)絡(luò))
networkResponse = chain.proceed(networkRequest);
} finally {
// If we're crashing on I/O or otherwise, don't leak the cache body.
if (networkResponse == null && cacheCandidate != null) {
closeQuietly(cacheCandidate.body());
}
}
// If we have a cache response too, then we're doing a conditional get.
//networkRequest不為null,cacheResponse也不為null
if (cacheResponse != null) {
//如果請求網(wǎng)絡(luò)響應(yīng)碼為304(緩存還可以用)
if (networkResponse.code() == HTTP_NOT_MODIFIED) {
Response response = cacheResponse.newBuilder()
.headers(combine(cacheResponse.headers(), networkResponse.headers()))
.sentRequestAtMillis(networkResponse.sentRequestAtMillis())
.receivedResponseAtMillis(networkResponse.receivedResponseAtMillis())
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
networkResponse.body().close();
// Update the cache after combining headers but before stripping the
// Content-Encoding header (as performed by initContentStream()).
cache.trackConditionalCacheHit();
//更新緩存
cache.update(cacheResponse, response);
return response;
} else {
closeQuietly(cacheResponse.body());
}
}
//networkRequest不為null,cacheResponse為null,
Response response = networkResponse.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
//有設(shè)置緩存目錄
if (cache != null) {
//有響應(yīng)體,并且能夠緩存
if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
// Offer this request to the cache.
//將從網(wǎng)絡(luò)請求到的響應(yīng)存到本地緩存目錄
CacheRequest cacheRequest = cache.put(response);
return cacheWritingResponse(cacheRequest, response);
}
//判斷緩存是否可用(只有 GET 請求的響應(yīng)能被緩存,否則就移除緩存)
if (HttpMethod.invalidatesCache(networkRequest.method())) {
try {
cache.remove(networkRequest);
} catch (IOException ignored) {
// The cache cannot be written.
}
}
}
return response;
}
CacheInterceptor的工作原理總結(jié):
- 查看本地是否有緩存,本地緩存是通過DiskLruCache 來存儲的,存儲的目錄是在OkHttpClient的builder.cache(Cache)中設(shè)置的,存儲的key為請求URL的MD5值
- 根據(jù)HTTP的緩存機制,也就是根據(jù)之前緩存的結(jié)果與當(dāng)前將要發(fā)送Request的header值,得出是進(jìn)行請求還是使用緩存,并用
networkRequest和cacheResponse標(biāo)識,同時根據(jù)這個兩個值創(chuàng)建緩存策略對象CacheStrategy- 根據(jù)緩存策略對象
CacheStrategy的networkRequest和cacheResponse標(biāo)識,判斷是請求還是使用緩存響應(yīng)- 如果當(dāng)前請求是請求網(wǎng)絡(luò)數(shù)據(jù),并且沒有緩存,在請求到數(shù)據(jù)后,存到本地緩存目錄
所以如果要使用OkHttp自帶的緩存,就需要后端人員配合,或者是自己使用網(wǎng)絡(luò)攔截器在請求到數(shù)據(jù)后,自己添加跟緩存相關(guān)的響應(yīng)Header。