OkHttp3中有五大攔截器美侦,分別是重試和重定向攔截器(RetryAndFollowUpInterceptor)产舞、橋接攔截器(BridgeInterceptor)、緩存攔截器(CacheInterceptor)菠剩、連接攔截器(ConnectInterceptor)易猫、請(qǐng)求服務(wù)器攔截器(CallServerInterceptor)
- 重試攔截器在交出(交給下一個(gè)攔截器)之前,負(fù)責(zé)判斷用戶是否取消了請(qǐng)求具壮;在獲得了結(jié)果之后准颓,會(huì)根據(jù)響應(yīng)碼判斷是否需要重定向,如果滿足條件那么就會(huì)啟動(dòng)執(zhí)行所有攔截器棺妓。
- 橋接攔截器在交出之前攘已,負(fù)責(zé)將HTTP協(xié)議必備的請(qǐng)求頭加入其中(如:Host)并添加一些默認(rèn)的行為(如:GZIP壓縮);在獲得了結(jié)果后怜跑,調(diào)用保存cookie接口并解析GZIP數(shù)據(jù)样勃。
- 緩存攔截器在交出之前,讀取并判斷是否使用緩存;獲得結(jié)果后判斷是否保存緩存彤灶。
- 連接攔截器在交出之前看幼,負(fù)責(zé)找到或者新建一個(gè)連接批旺,并獲得對(duì)應(yīng)的socket流幌陕;在獲得結(jié)果之后不進(jìn)行額外的處理。
- 請(qǐng)求服務(wù)器攔截器進(jìn)行真正的與服務(wù)器的通信汽煮,向服務(wù)器發(fā)送數(shù)據(jù)搏熄,解析讀取的響應(yīng)數(shù)據(jù)。
本文源碼解析基于OkHttp3.14
// RealCall.java
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
List<Interceptor> interceptors = new ArrayList<>();
interceptors.addAll(client.interceptors());
interceptors.add(new RetryAndFollowUpInterceptor(client));
interceptors.add(new BridgeInterceptor(client.cookieJar()));
interceptors.add(new CacheInterceptor(client.internalCache()));
interceptors.add(new ConnectInterceptor(client));
if (!forWebSocket) {
interceptors.addAll(client.networkInterceptors());
}
interceptors.add(new CallServerInterceptor(forWebSocket));
Interceptor.Chain chain = new RealInterceptorChain(interceptors, transmitter, null, 0,
originalRequest, this, client.connectTimeoutMillis(),
client.readTimeoutMillis(), client.writeTimeoutMillis());
boolean calledNoMoreExchanges = false;
try {
Response response = chain.proceed(originalRequest);
if (transmitter.isCanceled()) {
closeQuietly(response);
throw new IOException("Canceled");
}
return response;
} catch (IOException e) {
calledNoMoreExchanges = true;
throw transmitter.noMoreExchanges(e);
} finally {
if (!calledNoMoreExchanges) {
transmitter.noMoreExchanges(null);
}
}
}
// RealInterceptorChain.java
// 第一次進(jìn)入暇赤,index是0
public Response proceed(Request request, Transmitter transmitter, @Nullable Exchange exchange)
throws IOException {
if (index >= interceptors.size()) throw new AssertionError();
calls++;
// If we already have a stream, confirm that the incoming request will use it.
if (this.exchange != null && !this.exchange.connection().supportsUrl(request.url())) {
throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
+ " must retain the same host and port");
}
// If we already have a stream, confirm that this is the only call to chain.proceed().
if (this.exchange != null && calls > 1) {
throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
+ " must call proceed() exactly once");
}
// Call the next interceptor in the chain.
// 調(diào)用index+1的攔截器的RealInterceptorChain
RealInterceptorChain next = new RealInterceptorChain(interceptors, transmitter, exchange,
index + 1, request, call, connectTimeout, readTimeout, writeTimeout);
// 取出第0個(gè)攔截器
Interceptor interceptor = interceptors.get(index);
Response response = interceptor.intercept(next);
// Confirm that the next interceptor made its required call to chain.proceed().
if (exchange != null && index + 1 < interceptors.size() && next.calls != 1) {
throw new IllegalStateException("network interceptor " + interceptor
+ " must call proceed() exactly once");
}
// Confirm that the intercepted response isn't null.
if (response == null) {
throw new NullPointerException("interceptor " + interceptor + " returned null");
}
if (response.body() == null) {
throw new IllegalStateException(
"interceptor " + interceptor + " returned a response with no body");
}
return response;
}
一心例、重試和重定向攔截器(RetryAndFollowUpInterceptor)
重試和重定向攔截器主要分為重試和重定向兩部分。重試和重定向攔截器鞋囊,只處理響應(yīng)結(jié)果
1.重試
RetryAndFollowUpInterceptor攔截器完成止后,主要工作是intercept方法中進(jìn)行。
- (1)接收請(qǐng)求發(fā)出的時(shí)候產(chǎn)生的異常溜腐,判斷是路由異常還是IO異常
- (2)通過(guò)調(diào)用recover方法進(jìn)行重試
- (3)重試時(shí)判斷是否允許重試译株、判斷是不是重試異常、判斷是否有可以用來(lái)連接的路由線路
- (4)在允許重試的情況下挺益,出現(xiàn)協(xié)議異常歉糜、SSL握手異常中證書出現(xiàn)問(wèn)題、SSL握手異常望众,這里的SSL握手導(dǎo)致的異常匪补,第一種就是有證書,但是驗(yàn)證失敗烂翰,第二種其實(shí)就是沒有證書夯缺,出現(xiàn)這樣的異常是不可以重試的
- (5)如果允許重試,則有更多的線路
(1)RetryAndFollowUpInterceptor.intercept()
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RealInterceptorChain realChain = (RealInterceptorChain) chain;
// Transmitter對(duì)象,是在RealCall中初始化創(chuàng)建的呻逆,在Transmitter中就會(huì)初始化創(chuàng)建ConnectionPool
// 而ConnectionPool其實(shí)比較類似裝飾者模式肌似,封裝RealConnectionPool
Transmitter transmitter = realChain.transmitter();
int followUpCount = 0;
Response priorResponse = null;
// 重試和重定向攔截器內(nèi)部是采用一個(gè)無(wú)限死循環(huán)的while循環(huán),這樣做的目的就是為了在出現(xiàn)錯(cuò)誤的時(shí)候可以進(jìn)行請(qǐng)求重試等操作
while (true) {
transmitter.prepareToConnect(request);
if (transmitter.isCanceled()) {
throw new IOException("Canceled");
}
Response response;
boolean success = false;
try {
// 調(diào)用RealInterceptorChain.proceed方法润文,這個(gè)RealInterceptorChain對(duì)象
// 是在getResponseWithInterceptorChain()第一次調(diào)用RealInterceptorChain.proceed
// 的時(shí)候,在其內(nèi)部創(chuàng)建的index=1的RealInterceptorChain對(duì)象殿怜。
response = realChain.proceed(request, transmitter, null);
success = true;
} catch (RouteException e) {
// 路由溢出典蝌,連接未成功,請(qǐng)求沒有發(fā)出去头谜,在這里進(jìn)行重試
// 如果為true骏掀,說(shuō)明可以進(jìn)行重試,則不拋出異常,并且調(diào)用continue
// 這樣就繼續(xù)執(zhí)行下一次while循環(huán)截驮,繼續(xù)執(zhí)行請(qǐng)求操作
if (!recover(e.getLastConnectException(), transmitter, false, request)) {
throw e.getFirstConnectException();
}
continue;
} catch (IOException e) {
// 請(qǐng)求發(fā)出去了笑陈,但是和服務(wù)器通信失敗了(socket流正在讀寫數(shù)據(jù)的時(shí)候斷開連接)
boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
if (!recover(e, transmitter, requestSendStarted, request)) throw e;
continue;
} finally {
// The network call threw an exception. Release any resources.
if (!success) {
transmitter.exchangeDoneDueToException();
}
}
// 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();
}
Exchange exchange = Internal.instance.exchange(response);
Route route = exchange != null ? exchange.connection().route() : null;
// 重定向判斷,如果返回是null則不需要進(jìn)行重定向
Request followUp = followUpRequest(response, route);
// 不需要重定向葵袭,則直接返回請(qǐng)求結(jié)果
if (followUp == null) {
if (exchange != null && exchange.isDuplex()) {
transmitter.timeoutEarlyExit();
}
return response;
}
RequestBody followUpBody = followUp.body();
if (followUpBody != null && followUpBody.isOneShot()) {
return response;
}
closeQuietly(response.body());
if (transmitter.hasExchange()) {
exchange.detachWithViolence();
}
// 定義重定向的次數(shù)涵妥,最大為20次,一旦超過(guò)20次坡锡,則會(huì)拋出異常蓬网。
if (++followUpCount > MAX_FOLLOW_UPS) {
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}
request = followUp;
priorResponse = response;
}
}
(2)RetryAndFollowUpInterceptor.recover()
判斷是否能夠進(jìn)行重試,如果能夠則返回true表示可以進(jìn)行重試鹉勒。
不進(jìn)行重試的情況:
- 不允許重試的帆锋,則不進(jìn)行重試
- 只請(qǐng)求一次的,不進(jìn)行重試禽额;請(qǐng)求剛發(fā)起的不進(jìn)行重試
- 協(xié)議異常的不進(jìn)行重試
- 不是請(qǐng)求超時(shí)的不進(jìn)行重試
- SSL證書異常锯厢,比如證書損壞等不進(jìn)行重試
- SSL授權(quán)異常,比如過(guò)期等不進(jìn)行重試
- 沒有更多路由路線的脯倒,不進(jìn)行重試
反過(guò)來(lái)实辑,可以進(jìn)行重試的:滿足下面所有條件
- 設(shè)置允許進(jìn)行重試
- 不是只請(qǐng)求一次
- 是超時(shí)請(qǐng)求
- 不是SSL證書損壞
- 不是SSL證書過(guò)期
- 有多路由線路
private boolean recover(IOException e, Transmitter transmitter,
boolean requestSendStarted, Request userRequest) {
// 在配置okhttpClient是設(shè)置了不允許重試(默認(rèn)允許),則一旦發(fā)生請(qǐng)求失敗則不再進(jìn)行重試
if (!client.retryOnConnectionFailure()) return false;
// 由于requestSendStarted只在http2的io異常中為true盔憨,先不管http2
// 這里的requestIsOneShot為true徙菠,表示只請(qǐng)求一次,那么也不重試
if (requestSendStarted && requestIsOneShot(e, userRequest)) return false;
// 判斷是不是屬于重試的異常郁岩,如果是婿奔,則返回false
if (!isRecoverable(e, requestSendStarted)) return false;
// 有沒有可以用來(lái)連接的路由路線
if (!transmitter.canRetry()) return false;
// For failure recovery, use the same route selector with a new connection.
return true;
}
(3)RetryAndFollowUpInterceptor.isRecoverable()
判斷是否屬于重試的異常,在一些情況下出現(xiàn)的重試異常是不能進(jìn)行重試的问慎,如果可以進(jìn)行重試萍摊,可以判斷是否有多路路由可以切換,有則切換一條路由進(jìn)行重試如叼。
private boolean isRecoverable(IOException e, boolean requestSendStarted) {
// 出現(xiàn)協(xié)議異常冰木,不能重試
// 比如服務(wù)器返回的響應(yīng)碼是204或者205,但是response的body又是大于0的
// 因?yàn)?04的是服務(wù)器沒返回任何內(nèi)容
// 205是服務(wù)器重置內(nèi)容笼恰,但是沒返回任何內(nèi)容
if (e instanceof ProtocolException) {
return false;
}
// requestSendStarted認(rèn)為它一直為false(不管http2)踊沸,異常屬于socket超時(shí)異常,直接判定可以重試
if (e instanceof InterruptedIOException) {
return e instanceof SocketTimeoutException && !requestSendStarted;
}
// SSL握手異常中社证,證書出現(xiàn)問(wèn)題逼龟,不能重試
if (e instanceof SSLHandshakeException) {
// If the problem was a CertificateException from the X509TrustManager,
// do not retry.
if (e.getCause() instanceof CertificateException) {
return false;
}
}
// SSL握手未授權(quán)異常,不能重試
if (e instanceof SSLPeerUnverifiedException) {
// e.g. a certificate pinning error.
return false;
}
return true;
}
在isRecoverable()方法中判斷的異常主要包括下面三種:
(1)協(xié)議異常追葡,如果是那么直接判定不能重試腺律;(你的請(qǐng)求或者服務(wù)器的響應(yīng)本身就存在問(wèn)題奕短,沒有按照http協(xié)議來(lái)定義數(shù)據(jù),再重試也沒有用)
(比如在發(fā)起http請(qǐng)求的時(shí)候匀钧,沒有攜帶host:XXXXX翎碑, 這就是一個(gè)協(xié)議異常)
(2)超時(shí)異常,可能由于網(wǎng)絡(luò)波動(dòng)造成了Socket管道的超時(shí)之斯,那么是可以重試的日杈。
(3)SSL證書異常或者SSL驗(yàn)證失敗異常吊圾,前者是證書驗(yàn)證失敗达椰,后者可能就是壓根沒癮證書翰蠢,或者證書數(shù)據(jù)不正確项乒,則不能進(jìn)行重試。
2.重定向
如果請(qǐng)求結(jié)束后沒有發(fā)生異常梁沧,并不代表當(dāng)前獲得的響應(yīng)就是最終需要交給用戶的檀何,還需要進(jìn)一步來(lái)判斷是否需要重定向的判斷。重定向的判斷廷支,其實(shí)是在整個(gè)責(zé)任鏈執(zhí)行完成得到Response之后频鉴,再判斷是否需要進(jìn)行重定向的。
即在RetryAndFollowUpInterceptor.intercept方法中調(diào)用了followUpRequest方法來(lái)判斷是否需要進(jìn)行重定向恋拍。
(1)如果followUpRequest方法返回為null則不需要進(jìn)行重定向
(2)而在調(diào)用followUpRequest方法進(jìn)行判定是否需要重定向時(shí)垛孔,在OkHttp中對(duì)followUpRequest的次數(shù)做了判斷,重定向次數(shù)最大為20次
(1)RetryAndFollowUpInterceptor.followUpRequest()
該方法其實(shí)就是在RRetryAndFollowUpInterceptor.intercept方法執(zhí)行完完整的責(zé)任鏈之后施敢,做重定向處理判斷的周荐。
重定向一般是30X的響應(yīng)碼的時(shí)候,才需要僵娃,此時(shí)從響應(yīng)頭中取出Location的值作為重定向的url概作;但是也有一些其他的響應(yīng)碼需要進(jìn)行重定向,比如407默怨,使用了代碼讯榕,比如401需要身份驗(yàn)證,這些也需要進(jìn)行重定向匙睹;如果是返回響應(yīng)碼408的話愚屁,用戶請(qǐng)求超時(shí),這個(gè)情況其實(shí)可以認(rèn)為是重試痕檬,而不是重定向霎槐;如果是503的話,則是服務(wù)器不可用谆棺,但是要滿足響應(yīng)頭的Retry-After值為0栽燕,表示服務(wù)器還無(wú)法處理請(qǐng)求罕袋,需要過(guò)多少秒進(jìn)行請(qǐng)求,而重定向碍岔,則需要是在Retry-After=0的時(shí)候浴讯,其實(shí)這情況也是重試。
private Request followUpRequest(Response userResponse, @Nullable Route route) throws IOException {
if (userResponse == null) throw new IllegalStateException();
int responseCode = userResponse.code();
final String method = userResponse.request().method();
switch (responseCode) {
// 407 客戶端使用了HTTP代理服務(wù)器蔼啦,在請(qǐng)求頭中添加"Proxy-Author-ization"榆纽,
// 讓代理服務(wù)器授權(quán)
case HTTP_PROXY_AUTH:
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 需要身份驗(yàn)證,有些服務(wù)器接口需要驗(yàn)證使用者身份捏肢,在請(qǐng)求頭中添加Authorization
// 所以添加Authorization請(qǐng)求頭的方式奈籽,對(duì)于Okhttp3請(qǐng)求來(lái)說(shuō)可以有專門的方法
// 通過(guò)給OkHttpClient.Builder的authenticator方法設(shè)置
return client.authenticator().authenticate(route, userResponse);
case HTTP_PERM_REDIRECT:
case HTTP_TEMP_REDIRECT:
// 308 永久重定向
// 307 臨時(shí)重定向
// 如果請(qǐng)求方式不是GET活著HEAD,框架不會(huì)自動(dòng)重定向
if (!method.equals("GET") && !method.equals("HEAD")) {
return null;
}
// fall-through
case HTTP_MULT_CHOICE:
case HTTP_MOVED_PERM:
case HTTP_MOVED_TEMP:
case HTTP_SEE_OTHER:
// 300 301 302 303
// 這部分如果是允許重定向鸵赫,那么就需要根據(jù)響應(yīng)頭中的Location字段進(jìn)行重定向
// 然后取出Location字段的值
// 如果用戶不允許重定向衣屏,那就返回null
if (!client.followRedirects()) return null;
// 從響應(yīng)頭中取出location
String location = userResponse.header("Location");
if (location == null) return null;
// 根據(jù)location重新配置url
HttpUrl url = userResponse.request().url().resolve(location);
// 如果重新配置的url為null,說(shuō)明協(xié)議有問(wèn)題辩棒,取不出來(lái)HttpUrl狼忱,那就返回null,不進(jìn)行重定向
if (url == null) return null;
// 如果重定向在http到https之間切換一睁,需要檢查用戶是不是允許(默認(rèn)是允許)
boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());
if (!sameScheme && !client.followSslRedirects()) return null;
// Most redirects don't include a request body.
// 構(gòu)建重定向的request的builder
Request.Builder requestBuilder = userResponse.request().newBuilder();
/**
* 重定向請(qǐng)求中钻弄,只要不是PROPFIND請(qǐng)求,無(wú)論是POST還是其他的方法都要改為
* GET請(qǐng)求方式者吁,即只有PROPFIND請(qǐng)求才有請(qǐng)求體
*/
// 請(qǐng)求不是get與head
if (HttpMethod.permitsRequestBody(method)) {
final boolean maintainBody = HttpMethod.redirectsWithBody(method);
// 除了PROPFIND請(qǐng)求之外都改為GET請(qǐng)求
if (HttpMethod.redirectsToGet(method)) {
requestBuilder.method("GET", null);
} else {
RequestBody requestBody = maintainBody ? userResponse.request().body() : null;
requestBuilder.method(method, requestBody);
}
// 不是PROPFIND的請(qǐng)求窘俺,把請(qǐng)求頭中關(guān)于請(qǐng)求體的數(shù)據(jù)刪掉
if (!maintainBody) {
requestBuilder.removeHeader("Transfer-Encoding");
requestBuilder.removeHeader("Content-Length");
requestBuilder.removeHeader("Content-Type");
}
}
// 在跨主機(jī)重定向時(shí),刪除身份驗(yàn)證請(qǐng)求頭
if (!sameConnection(userResponse.request().url(), url)) {
requestBuilder.removeHeader("Authorization");
}
// 如果是需要重定向复凳,那么就構(gòu)建重定向的新請(qǐng)求瘤泪,進(jìn)行build,進(jìn)行重定向請(qǐng)求
return requestBuilder.url(url).build();
case HTTP_CLIENT_TIMEOUT:
// 408客戶端請(qǐng)求超時(shí)
// 408算是連接失敗了染坯,所以判斷用戶是不是允許重試
if (!client.retryOnConnectionFailure()) {
// The application layer has directed us not to retry the request.
return null;
}
RequestBody requestBody = userResponse.request().body();
if (requestBody != null && requestBody.isOneShot()) {
return null;
}
// 如果是本身這次的響應(yīng)就是重新請(qǐng)求的產(chǎn)物同時(shí)上一次之所以重新請(qǐng)求還是408
// 那么就不再重新請(qǐng)求
if (userResponse.priorResponse() != null
&& userResponse.priorResponse().code() == HTTP_CLIENT_TIMEOUT) {
// We attempted to retry and got another timeout. Give up.
return null;
}
// 如果服務(wù)器告訴我們了Retry-After多久后重試均芽,那框架不需要管
if (retryAfter(userResponse, 0) > 0) {
return null;
}
return userResponse.request();
case HTTP_UNAVAILABLE:
// 503服務(wù)器不可用,和408差不多单鹿,但是只在服務(wù)器告訴你Retry-After:0
// 意思就是立即重試掀宋,才重新請(qǐng)求
if (userResponse.priorResponse() != null
&& userResponse.priorResponse().code() == HTTP_UNAVAILABLE) {
// We attempted to retry and got another timeout. Give up.
return null;
}
if (retryAfter(userResponse, Integer.MAX_VALUE) == 0) {
// specifically received an instruction to retry without delay
return userResponse.request();
}
return null;
default:
return null;
}
}
二、橋接攔截器
BridgeInterceptor用于連接應(yīng)用程序和服務(wù)器的橋梁仲锄,我們發(fā)出的請(qǐng)求將會(huì)經(jīng)過(guò)它的處理才能發(fā)給服務(wù)器劲妙,比如設(shè)置請(qǐng)求頭內(nèi)容長(zhǎng)度、編碼儒喊、gzip壓縮镣奋、cookie等;獲取響應(yīng)后保存Cookie等操作怀愧。
請(qǐng)求頭 | 說(shuō)明 |
---|---|
Content-Type | 請(qǐng)求體類型侨颈,如:application/x-www-form-urlencoded |
Content-Length/Transfer-Encoding | 請(qǐng)求體解析方式 |
Host | 請(qǐng)求的主機(jī)站點(diǎn) |
Connection: Keep-Alive | 保持長(zhǎng)連接 |
Accept-Encoding: gzip | 接收響應(yīng)支持gizp壓縮 |
Cookie | cookie身份辨別 |
User-Agent | 請(qǐng)求的用戶信息余赢,如:操作系統(tǒng)、瀏覽器等 |
在補(bǔ)全了請(qǐng)求頭后交給下一個(gè)攔截器處理哈垢,得到響應(yīng)后妻柒,主要干兩件事:
(1)保持cookie,在下次請(qǐng)求則會(huì)讀取對(duì)應(yīng)的數(shù)據(jù)設(shè)置進(jìn)入請(qǐng)求頭耘分,默認(rèn)的CookieJar不提供實(shí)現(xiàn)
需要通過(guò)OkhttpClient.builder().cookieJar().build()
在cookieJar()方法中举塔,實(shí)現(xiàn)CookieJar接口,然后自己保存求泰,自己load
(2)如果使用gzip返回的數(shù)據(jù)央渣,則使用GzipSource包裝便于解析
(1)BridgeInterceptor#intercept
@Override public Response intercept(Chain chain) throws IOException {
Request userRequest = chain.request();
Request.Builder requestBuilder = userRequest.newBuilder();
RequestBody body = userRequest.body();
// 首先補(bǔ)全請(qǐng)求頭中的信息
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");
}
List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
if (!cookies.isEmpty()) {
requestBuilder.header("Cookie", cookieHeader(cookies));
}
if (userRequest.header("User-Agent") == null) {
requestBuilder.header("User-Agent", Version.userAgent());
}
// 請(qǐng)求下一個(gè)攔截器,獲取響應(yīng)信息
Response networkResponse = chain.proceed(requestBuilder.build());
HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
Response.Builder responseBuilder = networkResponse.newBuilder()
.request(userRequest);
// 如果使用了gzip渴频,則通過(guò)GzipSource包裝請(qǐng)求體數(shù)據(jù)
if (transparentGzip
&& "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))
&& HttpHeaders.hasBody(networkResponse)) {
GzipSource responseBody = new GzipSource(networkResponse.body().source());
Headers strippedHeaders = networkResponse.headers().newBuilder()
.removeAll("Content-Encoding")
.removeAll("Content-Length")
.build();
responseBuilder.headers(strippedHeaders);
String contentType = networkResponse.header("Content-Type");
responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
}
return responseBuilder.build();
}
三芽丹、緩存攔截器
CacheInterceptor緩存攔截器,在發(fā)出請(qǐng)求之前枉氮,判斷是否命中緩存志衍。如果命中則可以不請(qǐng)求,直接使用緩存的響應(yīng)(只存在GET請(qǐng)求的緩存)
步驟:
- (1)從緩存中獲得對(duì)應(yīng)請(qǐng)求的響應(yīng)緩存
- (2)創(chuàng)建CacheStrategy聊替,創(chuàng)建時(shí)會(huì)判斷是否能夠使用緩存,在CacheStrategy中存在兩個(gè)成員:networkRequest和cacheResponse培廓。組合情況如下:
networkRequest | cacheResponse | 說(shuō)明 |
---|---|---|
null | not null | 直接使用緩存 |
not null | null | 向服務(wù)器發(fā)起請(qǐng)求 |
null | null | 直接gg惹悄,okhttp直接返回504 |
not null | not null | 發(fā)起請(qǐng)求,若得到響應(yīng)為304(無(wú)修改)肩钠,則更新緩存響應(yīng)并返回 |
networkRequest是網(wǎng)絡(luò)請(qǐng)求對(duì)象泣港,cacheResponse是緩存結(jié)果對(duì)象,通過(guò)這兩個(gè)對(duì)象的組合進(jìn)行判定是否需要執(zhí)行下一步的攔截器价匠。
如果是networkRequest為null的時(shí)候当纱,需要考慮cacheResponse是否為null,如果cacheResponse不為null的話踩窖,則可以使用緩存坡氯,如果為null則返回504請(qǐng)求失敗洋腮;如果networkRequest不為null箫柳,則需要判斷cacheResponse是否為null,如果cacheResponse為null則進(jìn)行網(wǎng)絡(luò)請(qǐng)求啥供,如果不為null悯恍,則發(fā)起請(qǐng)求,請(qǐng)求響應(yīng)碼為304的話伙狐,則使用緩存涮毫,否則使用請(qǐng)求結(jié)果瞬欧。
- (3)交給下一個(gè)責(zé)任鏈繼續(xù)處理
- (4)后續(xù)工作,返回304則用緩存的響應(yīng)罢防;否則使用網(wǎng)絡(luò)響應(yīng)并緩存本次響應(yīng)(只緩存GET請(qǐng)求的響應(yīng))
1.緩存策略
依賴于CacheStrategy黍判。相關(guān)請(qǐng)求頭和響應(yīng)頭。
響應(yīng)頭 | 說(shuō)明 | 例子 |
---|---|---|
Date | 消息發(fā)送的時(shí)間 | Date:Sat,18 Nov 2028 06:17:41 GMT |
Expires | 資源過(guò)期的時(shí)間 | Expires:Sat, 18 Nov 2028 06:17:41 GMT |
Last-Modified | 資源最后修改時(shí)間 | Last-Modified:Fri,22 Jul 2016 02:57:17 GMT |
Etag | 資源在服務(wù)器的唯一標(biāo)識(shí) | ETag:"16df0-5383097a03d40" |
Age | 服務(wù)器用緩存響應(yīng)請(qǐng)求篙梢,該緩存從產(chǎn)生到現(xiàn)在經(jīng)過(guò)多長(zhǎng)時(shí)間(秒) | Age:3825683 |
Cache-Control | - | - |
請(qǐng)求頭 | 說(shuō)明 | 例子 |
---|---|---|
If-Modified-Since | 服務(wù)器沒有在指定的時(shí)間后修改請(qǐng)求對(duì)應(yīng)資源顷帖,返回304(無(wú)修改) | If-Modified-Since: Fri, 22 Jul 2016 02:57:17 GMT |
If-None-Match | 服務(wù)器將其余請(qǐng)求資源對(duì)應(yīng)的Etag值進(jìn)行比較,匹配返回304 | If-None-Match:"16df0-5383097a03d40" |
Cache-Control | - | - |
(1)Cache-Control
Cache-Control可以在請(qǐng)求頭中存在渤滞,也可以在響應(yīng)頭中存在贬墩,對(duì)應(yīng)的value可以設(shè)置多種組合:
max-age=[秒]:資源最大有效時(shí)間
public:表明該資源可以被任何用戶緩存,比如客戶端妄呕,代理服務(wù)器等都可以緩存資源陶舞;
private:表明該資源只能被單個(gè)用戶緩存,默認(rèn)是private
no-store:資源不允許被緩存
no-cache:請(qǐng)求不使用緩存(這里其實(shí)是對(duì)比緩存使用绪励,通過(guò)比較Etag和Last-Modified)
immutable:響應(yīng)資源不會(huì)改變
min-fresh=[秒]:請(qǐng)求緩存最小新鮮度(用戶認(rèn)為這個(gè)緩存有效的時(shí)長(zhǎng))
must-revalidate:可以緩存肿孵,但是必須再想服務(wù)器做校驗(yàn)
max-stale=[秒]:請(qǐng)求緩存過(guò)期后多久內(nèi)仍然有效
(2)強(qiáng)制緩存的依據(jù)
Expires:服務(wù)器返回給客戶端的數(shù)據(jù)到期時(shí)間,如果下一個(gè)請(qǐng)求的時(shí)間小于到期時(shí)間疏魏,則可以直接使用緩存服務(wù)器里的數(shù)據(jù)停做。Http1.0中的。所以這個(gè)的作用基本可以忽略大莫。因?yàn)檫@個(gè)時(shí)間是由服務(wù)器來(lái)規(guī)定蛉腌,而客戶端的時(shí)間和服務(wù)器的時(shí)間是會(huì)存在誤差的。
Cache-Control:private只厘、publiic烙丛、max-age=xxx、no-cache羔味、no-store這是一系列的緩存策略河咽。
Expires和Cache-Control同時(shí)存在的時(shí)候,Cache-Control的優(yōu)先級(jí)更高
(3)對(duì)比緩存的依據(jù)(Cache-Control設(shè)置為no-cache赋元,是響應(yīng)頭)
Last-Modified/If-Modified-Since
對(duì)比緩存會(huì)依賴于Last-Modified/If-Modified-Since
當(dāng)服務(wù)器返回?cái)?shù)據(jù)的時(shí)候忘蟹,告訴客戶端Last-Modified時(shí)間
客戶端再次請(qǐng)求If-Modified-Since與最后一次修改時(shí)間做對(duì)比,如果是大于Last-Modified則資源修改過(guò)们陆,如果是小于Last-Modified寒瓦,則沒有修改過(guò),返回304
Etag/If-None-Match(優(yōu)先級(jí)比Last-Modified高)
Etag:當(dāng)前資源在服務(wù)器的唯一標(biāo)識(shí)UUID(生成規(guī)則由服務(wù)器規(guī)定)服務(wù)器返回
再次請(qǐng)求If-None-Match將Etag帶到服務(wù)端去坪仇,服務(wù)器拿到If-None-Match之后杂腰,就會(huì)判斷與etag是否相等,如果相等椅文,就返回304
304一般都是網(wǎng)絡(luò)請(qǐng)求框架自己處理喂很,如果不是自己開發(fā)框架惜颇,則一般不會(huì)處理304。
當(dāng)客戶端需要發(fā)送相同的請(qǐng)求時(shí)少辣,根據(jù)Date + Cache-control來(lái)判斷是否緩存過(guò)期凌摄,如果過(guò)期了,會(huì)在請(qǐng)求中攜帶If-Modified-Since和If-None-Match兩個(gè)頭漓帅。兩個(gè)頭的值分別是響應(yīng)中Last-Modified和ETag頭的值锨亏。服務(wù)器通過(guò)這兩個(gè)頭判斷本地資源未發(fā)生變化,客戶端不需要重新下載忙干,返回304響應(yīng)器予。說(shuō)明,請(qǐng)求頭中有If-Modified-Since和If-None-Match兩個(gè)捐迫,則會(huì)發(fā)起請(qǐng)求乾翔,這個(gè)請(qǐng)求是有可能返回304,表示緩存雖然過(guò)期施戴,但是依然可以繼續(xù)使用
2.緩存詳細(xì)流程
如果從緩存中獲得本次請(qǐng)求URL對(duì)應(yīng)的Response反浓,首先會(huì)從響應(yīng)中獲得以上數(shù)據(jù)備用。
CacheStrategy是一個(gè)緩存策略類赞哗,該類告訴CacheInterceptor是使用緩存還是使用網(wǎng)絡(luò)請(qǐng)求雷则;
Cache是封裝了實(shí)際的緩存操作;
DiskLruCache:Cache基于DiskLruCache懈玻;
在CacheInterceptor中使用的是InternalCache對(duì)象巧婶,該對(duì)象其實(shí)是在OkHttp3中的Cache類中實(shí)現(xiàn)的接口實(shí)現(xiàn)類對(duì)象
@Override public Response intercept(Chain chain) throws IOException {
// OkHttp的緩存攔截器,只對(duì)get請(qǐng)求有效涂乌。并且需要配置cache
Response cacheCandidate = cache != null
? cache.get(chain.request())
: null;
long now = System.currentTimeMillis();
// 這里的cacheCandidate是從本地緩存中獲取的Response
// 根據(jù)請(qǐng)求對(duì)象Request獲取到該接口請(qǐng)求對(duì)應(yīng)的響應(yīng)緩存
// 該類其實(shí)就是緩存策略類,主要就是用來(lái)決定最后是進(jìn)行網(wǎng)絡(luò)請(qǐng)求還是從緩存獲取
CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
Request networkRequest = strategy.networkRequest;
Response cacheResponse = strategy.cacheResponse;
// 如果cache不為null英岭,則更新統(tǒng)計(jì)指標(biāo)
// 主要是更新:請(qǐng)求次數(shù)湾盒、使用網(wǎng)絡(luò)請(qǐng)求次數(shù)、使用緩存次數(shù)
if (cache != null) {
cache.trackResponse(strategy);
}
// 如果緩存的cacheResponse==null诅妹,說(shuō)明緩存不可用罚勾,則關(guān)閉
if (cacheCandidate != null && cacheResponse == null) {
closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
}
// 如果網(wǎng)絡(luò)請(qǐng)求和本地緩存都為null,則構(gòu)造一個(gè)504的Response結(jié)果
// 提示504錯(cuò)誤
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();
}
// 如果網(wǎng)絡(luò)請(qǐng)求為null吭狡,而cacheResponse不為null尖殃,則直接使用緩存數(shù)據(jù)
if (networkRequest == null) {
return cacheResponse.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.build();
}
// 網(wǎng)絡(luò)請(qǐng)求不為null,那么有兩種情況划煮,一種是本地緩存為null送丰,一種是不為null
Response networkResponse = null;
try {
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());
}
}
// 如果本地緩存結(jié)果不為null,那么判斷網(wǎng)絡(luò)請(qǐng)求的結(jié)果
if (cacheResponse != null) {
// 判斷網(wǎng)絡(luò)請(qǐng)求結(jié)果是否為304弛秋,如果是304器躏,則使用本地緩存
// 如果不是304俐载,則關(guān)閉本地緩存,使用網(wǎng)絡(luò)請(qǐng)求結(jié)果
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());
}
}
Response response = networkResponse.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
// 如果使用網(wǎng)絡(luò)請(qǐng)求結(jié)果登失,需要判斷是否可以進(jìn)行緩存遏佣,如果可以,則將網(wǎng)絡(luò)請(qǐng)求結(jié)果緩存到本地
if (cache != null) {
if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
// Offer this request to the cache.
CacheRequest cacheRequest = cache.put(response);
return cacheWritingResponse(cacheRequest, response);
}
if (HttpMethod.invalidatesCache(networkRequest.method())) {
try {
cache.remove(networkRequest);
} catch (IOException ignored) {
// The cache cannot be written.
}
}
}
return response;
}
(1)CacheStrategy
緩存策略判斷流程:
- 緩存是否存在揽浙,不存在則進(jìn)行網(wǎng)絡(luò)請(qǐng)求状婶。即cacheResponse=null
- 如果是https請(qǐng)求,但是緩存中沒有握手的信息馅巷,則不使用緩存cacheResponse=null
- 響應(yīng)碼以及響應(yīng)頭判斷膛虫。緩存中的響應(yīng)碼為200,203令杈,204走敌,300,301逗噩,404掉丽,405,410异雁,414捶障,501,308的情況下纲刀,只判斷服務(wù)器設(shè)置了Cache-Control:no-store项炼,則不使用緩存;如果是302示绊,307則需要存在Expires:時(shí)間锭部、CacheControl:max-age/public/private
- 用戶的請(qǐng)求配置。如果Cache-Control的值是noCache或者網(wǎng)絡(luò)請(qǐng)求的Request中的If-Modified-Since或者If-None-Match不為null,第一個(gè)情況就是直接請(qǐng)求,第二種情況可能會(huì)返回304幅骄,表示緩存過(guò)期
- 資源是否不變
- 響應(yīng)的緩存是否有效
CacheStrategy.Factory()
這里主要是通過(guò)工廠類對(duì)象,初始化本地緩存響應(yīng)頭字段湃窍,并且初始化CacheStrategy緩存策略類對(duì)象
public Factory(long nowMillis, Request request, Response cacheResponse) {
this.nowMillis = nowMillis;
this.request = request;
this.cacheResponse = cacheResponse;
// 如果該請(qǐng)求的對(duì)應(yīng)的本地緩存不為null,則取出該緩存的響應(yīng)頭字段
if (cacheResponse != null) {
// 對(duì)應(yīng)響應(yīng)的請(qǐng)求發(fā)出的本地實(shí)際和接收到響應(yīng)的本地實(shí)際
this.sentRequestMillis = cacheResponse.sentRequestAtMillis();
this.receivedResponseMillis = cacheResponse.receivedResponseAtMillis();
Headers headers = cacheResponse.headers();
for (int i = 0, size = headers.size(); i < size; i++) {
// 遍歷響應(yīng)頭匪傍,取出對(duì)應(yīng)的字段name和value
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)) {
// 服務(wù)器返回給客戶端的數(shù)據(jù)到期時(shí)間
expires = HttpDate.parse(value);
} else if ("Last-Modified".equalsIgnoreCase(fieldName)) {
// 服務(wù)器返回給客戶端的最后修改時(shí)間
lastModified = HttpDate.parse(value);
lastModifiedString = value;
} else if ("ETag".equalsIgnoreCase(fieldName)) {
// 服務(wù)器返回給客戶端的該數(shù)據(jù)資源在服務(wù)器端的uuid
etag = value;
} else if ("Age".equalsIgnoreCase(fieldName)) {
ageSeconds = HttpHeaders.parseSeconds(value, -1);
}
}
}
}
CacheStrategy.get()
CacheStrategy.get()是用來(lái)判斷緩存的命中您市,會(huì)調(diào)用CacheStrategy的get()方法。其實(shí)就是通過(guò)一系列的緩存策略役衡,通過(guò)是否使用緩存的一系列邏輯判斷茵休,構(gòu)建一個(gè)CacheStrategy策略
public CacheStrategy get() {
CacheStrategy candidate = getCandidate();
// 如果可以使用緩存,那networkRequest必定為null;
// 指定了只使用緩存但是networkRequest又不會(huì)null
// 則會(huì)沖突泽篮,攔截器就會(huì)返回504盗尸,請(qǐng)求失敗
// 這里candidate的networkRequest不為null,且request的onlyIfCached為true是意味著不使用網(wǎng)絡(luò)
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;
}
CacheStrategy.getCandidate()
private CacheStrategy getCandidate() {
// TODO:第一步:判斷緩存是否存在
if (cacheResponse == null) {
return new CacheStrategy(request, null);
}
// TODO:第二步:https請(qǐng)求的緩存帽撑。如果本地緩存沒有握手泼各,則進(jìn)行網(wǎng)絡(luò)請(qǐng)求
if (request.isHttps() && cacheResponse.handshake() == null) {
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.
// TODO:第三步:響應(yīng)碼以及響應(yīng)頭
// 如果緩存不可用,則進(jìn)行網(wǎng)絡(luò)請(qǐng)求
if (!isCacheable(cacheResponse, request)) {
return new CacheStrategy(request, null);
}
// TODO:第四步:用戶的請(qǐng)求配置
// 如果Cache-Control的值是noCache或者網(wǎng)絡(luò)請(qǐng)求的Request中的If-Modified-Since或者If-None-Match不為null亏拉,則進(jìn)行網(wǎng)絡(luò)請(qǐng)求
// Request中有If-Modified-Since或者If-None-Match扣蜻,說(shuō)明本地緩存已經(jīng)被判定是過(guò)期的
// 則需要請(qǐng)求服務(wù)器,然后服務(wù)器會(huì)通過(guò)接收到的If-Modified-Since或者If-None-Match判斷數(shù)據(jù)是否發(fā)生改變
// 如果發(fā)生了改變及塘,則返回200莽使,并且返回新的數(shù)據(jù),如果沒有發(fā)生改變笙僚,則返回304芳肌,使用本地緩存數(shù)據(jù)
// 這里的網(wǎng)絡(luò)請(qǐng)求主要是請(qǐng)求查看是否還可以使用緩存
// 但是OkHttp3的框架中,請(qǐng)求對(duì)象Request的CacheControl設(shè)置為noCache的時(shí)候
// 表示的就是請(qǐng)求的時(shí)候不使用緩存
// 請(qǐng)求頭中設(shè)置Cache-Control:no-cache肋层,表示是告訴服務(wù)器本地?zé)o緩存
// 如果是響應(yīng)頭設(shè)置Cache-Control:no-cache則是表示需要重新請(qǐng)求服務(wù)器進(jìn)行驗(yàn)證
CacheControl requestCaching = request.cacheControl();
if (requestCaching.noCache() || hasConditions(request)) {
return new CacheStrategy(request, null);
}
// TODO:第五步:資源是否不變
CacheControl responseCaching = cacheResponse.cacheControl();
/** 這是3.10的源碼亿笤,在3.10中會(huì)判斷緩存響應(yīng)中是否存在Cache-Control: immutable
* 如果存在,則響應(yīng)資源將一直不會(huì)改變栋猖,可以使用緩存净薛。
*if (responseCaching.immutable()) {
* return new CacheStrategy(null, cacheResponse);
*}
*/
// TODO:第六步:響應(yīng)的緩存是否有效
// 6.1:獲得緩存的響應(yīng)從創(chuàng)建到現(xiàn)在的時(shí)間
long ageMillis = cacheResponseAge();
// 6.2:獲取這個(gè)響應(yīng)有效緩存時(shí)長(zhǎng)(緩存有效時(shí)間)與minFreshMillis的區(qū)別
// 其實(shí)就是minFreshMillis是請(qǐng)求認(rèn)為的緩存有效時(shí)間
long freshMillis = computeFreshnessLifetime();
// 如果請(qǐng)求中指定了max-age表示指定了能拿的緩存有效時(shí)長(zhǎng),就需要總和響應(yīng)
// 有效緩存時(shí)長(zhǎng)與請(qǐng)求能拿緩存的時(shí)長(zhǎng)蒲拉,獲得最小能夠使用響應(yīng)緩存的時(shí)長(zhǎng)
// max-age是資源最大有效時(shí)間
if (requestCaching.maxAgeSeconds() != -1) {
freshMillis = Math.min(freshMillis, SECONDS.toMillis(requestCaching.maxAgeSeconds()));
}
// 6.3:請(qǐng)求包含Cache-control: min-fresh=[秒] 能夠使用還未過(guò)指定時(shí)間
// 的緩存(用戶請(qǐng)求認(rèn)為的緩存有效時(shí)間肃拜,最小新鮮度)
long minFreshMillis = 0;
if (requestCaching.minFreshSeconds() != -1) {
minFreshMillis = SECONDS.toMillis(requestCaching.minFreshSeconds());
}
// 6.4
// 6.4.1:Cache-Control:must-revalidate 可緩存但是必須再向服務(wù)器進(jìn)行確認(rèn)
// 6.4.2:Cache-Control:max-state=[秒] 緩存過(guò)期后還能使用指定的時(shí)長(zhǎng),
// 如果未指定多少秒雌团,則表示無(wú)論過(guò)期多長(zhǎng)時(shí)間都可以燃领;如果指定了,則只要是
// 指定時(shí)間內(nèi)就能使用緩存
// 如果前者不滿足锦援,則自動(dòng)忽略后者柿菩。只有不是必須向服務(wù)器進(jìn)行確認(rèn)的情況下
// 才會(huì)判斷緩存的過(guò)期時(shí)間
long maxStaleMillis = 0;
if (!responseCaching.mustRevalidate() && requestCaching.maxStaleSeconds() != -1) {
maxStaleMillis = SECONDS.toMillis(requestCaching.maxStaleSeconds());
}
// 6.5:不需要與服務(wù)器驗(yàn)證有效性 && 獲得緩存的響應(yīng)從創(chuàng)建到現(xiàn)在的時(shí)間 +
// 請(qǐng)求認(rèn)為的緩存有效時(shí)間(最小新鮮度) 小于 緩存有效時(shí)間 + 過(guò)期后還可以使用的時(shí)間
// 如果滿足條件,則允許使用緩存
if (!responseCaching.noCache() && ageMillis + minFreshMillis < freshMillis + maxStaleMillis) {
Response.Builder builder = cacheResponse.newBuilder();
// 如果緩存的響應(yīng)從創(chuàng)建到現(xiàn)在的時(shí)間 + 請(qǐng)求認(rèn)為的緩存有效時(shí)長(zhǎng)
// 小于 緩存有效時(shí)間雨涛,這樣的情況就是已經(jīng)過(guò)期,但是沒有超過(guò)過(guò)期后繼續(xù)
// 使用時(shí)長(zhǎng)懦胞,還是可以繼續(xù)使用替久,添加相應(yīng)的頭部字段
if (ageMillis + minFreshMillis >= freshMillis) {
builder.addHeader("Warning", "110 HttpURLConnection \"Response is stale\"");
}
// 如果緩存已經(jīng)過(guò)期一天,并且響應(yīng)中沒有設(shè)置過(guò)期時(shí)間也需要添加警告
long oneDayMillis = 24 * 60 * 60 * 1000L;
if (ageMillis > oneDayMillis && isFreshnessLifetimeHeuristic()) {
builder.addHeader("Warning", "113 HttpURLConnection \"Heuristic expiration\"");
}
// 使用緩存中的數(shù)據(jù)
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.
// 第七步:緩存過(guò)期處理
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 {
// 意味著無(wú)法與服務(wù)器發(fā)起比較躏尉,只能重新請(qǐng)求
return new CacheStrategy(request, null); // No condition! Make a regular request.
}
// 添加請(qǐng)求頭
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);
}
3.解析CacheStrategy.getCandidate()
CacheStrategy.getCandidate()其實(shí)就是獲取CacheStrategy對(duì)象蚯根,其內(nèi)部根據(jù)一些時(shí)間和請(qǐng)求頭的配置
(1)第一步:緩存是否存在
cacheResponse是從緩存中找到的響應(yīng),如果為null,說(shuō)明緩存不存在颅拦,則創(chuàng)建對(duì)應(yīng)的CacheStrategy實(shí)例對(duì)象蒂誉,且只存在networkRequest,即需要發(fā)起網(wǎng)絡(luò)請(qǐng)求距帅。
(2)第二步:https請(qǐng)求的緩存
如果本次是https緩存,但是緩存中缺少必要的握手信息碌秸,則緩存無(wú)效绍移,依然創(chuàng)建對(duì)應(yīng)的CacheStrategy實(shí)例對(duì)象,且只有networkRequest讥电,即需要發(fā)起網(wǎng)絡(luò)請(qǐng)求
(3)第三步:響應(yīng)碼以及響應(yīng)頭
判斷邏輯在isCacheable方法中蹂窖。這里其實(shí)就是判斷該請(qǐng)求是否可以使用緩存
public static boolean isCacheable(Response response, Request request) {
// Always go to network for uncacheable response codes (RFC 7231 section 6.1),
// This implementation doesn't support caching partial content.
switch (response.code()) {
case HTTP_OK:
case HTTP_NOT_AUTHORITATIVE:
case HTTP_NO_CONTENT:
case HTTP_MULT_CHOICE:
case HTTP_MOVED_PERM:
case HTTP_NOT_FOUND:
case HTTP_BAD_METHOD:
case HTTP_GONE:
case HTTP_REQ_TOO_LONG:
case HTTP_NOT_IMPLEMENTED:
case StatusLine.HTTP_PERM_REDIRECT:
// These codes can be cached unless headers forbid it.
break;
case HTTP_MOVED_TEMP:
case StatusLine.HTTP_TEMP_REDIRECT:
// These codes can only be cached with the right response headers.
// http://tools.ietf.org/html/rfc7234#section-3
// s-maxage is not checked because OkHttp is a private cache that should ignore s-maxage.
if (response.header("Expires") != null
|| response.cacheControl().maxAgeSeconds() != -1
|| response.cacheControl().isPublic()
|| response.cacheControl().isPrivate()) {
break;
}
// Fall-through.
default:
// All other codes cannot be cached.
return false;
}
// A 'no-store' directive on request or response prevents the response from being cached.
return !response.cacheControl().noStore() && !request.cacheControl().noStore();
}
緩存中的響應(yīng)碼為200,203恩敌,204瞬测,300,301纠炮,404月趟,405,410抗碰,414狮斗,501,308的情況下弧蝇,只判斷服務(wù)器設(shè)置了Cache-Control:no-store(資源不能被緩存)碳褒,如果服務(wù)器沒有設(shè)置,則response.cacheControl().noStore()為false看疗,取反即為true沙峻,那么在if (!isCacheable(cacheResponse, request))得到的就是false;如果服務(wù)器設(shè)置了資源不能被緩存两芳,則說(shuō)明需要進(jìn)行網(wǎng)絡(luò)請(qǐng)求摔寨,則直接創(chuàng)建CacheStrategy實(shí)例,且只傳入networkRequest怖辆。
如果響應(yīng)碼是302是复,307(重定向),則需要進(jìn)一步判斷是否存在一些允許緩存的響應(yīng)頭竖螃。如果存在Expires淑廊,或者Cache-Control的值為max-age=[秒]:資源最大有效時(shí)間,public:表明該資源可以被任何用戶緩存特咆,比如客戶端季惩,private:表明該資源只能被單個(gè)用戶緩存。
在這里Expires是服務(wù)器返回給客戶端的數(shù)據(jù)到期時(shí)間
在同時(shí)沒有設(shè)置Cahce-Control: no-store的時(shí)候,就可以進(jìn)一步判斷緩存是否可以使用画拾。如果依然設(shè)置了Cache-Control: no-store啥繁,則不管是任何響應(yīng)碼,都不能緩存青抛,都只能直接進(jìn)行網(wǎng)絡(luò)請(qǐng)求旗闽。
所以綜合判斷優(yōu)先級(jí)如下:
- 響應(yīng)碼不為200,203脂凶,204宪睹,300,301蚕钦,404亭病,405,410嘶居,414罪帖,501,308邮屁,302整袁,307緩存不可用
- 當(dāng)響應(yīng)碼為302,307時(shí)佑吝,沒有包含Expires或者Cache-Control沒有設(shè)置max-age坐昙、public、private三個(gè)中的一個(gè)芋忿,則緩存不可用
- 當(dāng)存在Cache-Control:no-store響應(yīng)頭炸客,則緩存不可用
(4)第四步:用戶的請(qǐng)求配置
// 請(qǐng)求頭中設(shè)置Cache-Control:no-cache,表示是告訴服務(wù)器本地?zé)o緩存
// 如果是響應(yīng)頭設(shè)置Cache-Control:no-cache則是表示需要重新請(qǐng)求服務(wù)器進(jìn)行驗(yàn)證
CacheControl requestCaching = request.cacheControl();
if (requestCaching.noCache() || hasConditions(request)) {
return new CacheStrategy(request, null);
}
private static boolean hasConditions(Request request) {
return request.header("If-Modified-Since") != null
|| request.header("If-None-Match") != null;
}
依然是判斷資源是否允許緩存戈钢,如果是不允許的痹仙,則直接創(chuàng)建CacheStrategy對(duì)象實(shí)例,參數(shù)傳入networkRequest對(duì)象殉了。但是如果是允許的开仰,則在這里就需要先對(duì)用戶本次發(fā)起的請(qǐng)求進(jìn)行判定,如果用戶指定了If-Modified-Since或者If-None-Match(因?yàn)檫@里還沒到緩存過(guò)期處理部分)薪铜,說(shuō)明可能是大于最后一次修改時(shí)間或者是資源id并不匹配众弓,所以需要重新請(qǐng)求。如果允許緩存隔箍,且請(qǐng)求頭中沒有If-Modified-Since和If-None-Match均為null田轧,則說(shuō)明有緩存,可以進(jìn)行下一步的判斷緩存是否可以使用鞍恢。
(5)第五步:資源是否不變
在OkHttp3.10的源碼中,CacheStrategy.getCandidate()中存在下面判斷:
if (responseCaching.immutable()) {
return new CacheStrategy(null, cacheResponse);
}
但是在OkHttp3.14的源碼中,這部分判斷已經(jīng)去除帮掉。如果響應(yīng)頭中包含了Cache-Control: immutable弦悉,則說(shuō)明資源不會(huì)改變,則在用戶請(qǐng)求時(shí)蟆炊,可以直接使用緩存而不需要請(qǐng)求稽莉,所以在創(chuàng)建CacheStrategy對(duì)象實(shí)例的時(shí)候,networkRequest參數(shù)傳的是null涩搓,而Response傳入的就是cacheResponse污秆。
(6)響應(yīng)的緩存有效期
在這里,進(jìn)一步根據(jù)緩存響應(yīng)中的信息判斷是否處于有效期內(nèi)昧甘。如果滿足:
緩存存活時(shí)間 < 緩存新鮮度 - 緩存最小新鮮度 + 過(guò)期后繼續(xù)使用時(shí)長(zhǎng)
緩存存活時(shí)間:其實(shí)就是緩存從創(chuàng)建到現(xiàn)在已經(jīng)持續(xù)了多久的時(shí)間良拼,在OkHttp的CacheStrategy.getCandidate()方法中,即ageMillis
private long cacheResponseAge() {
// 代表客戶端收到響應(yīng)到服務(wù)器發(fā)出響應(yīng)的一個(gè)時(shí)間差
// servedDate是從緩存中獲得Data響應(yīng)頭對(duì)應(yīng)的時(shí)間(服務(wù)器發(fā)出本響應(yīng)的時(shí)間)
// receivedResponseMillis為本次響應(yīng)(cacheResponse)對(duì)應(yīng)的客戶端接收到響應(yīng)的時(shí)間
long apparentReceivedAge = servedDate != null
? Math.max(0, receivedResponseMillis - servedDate.getTime())
: 0;
// 代表客戶端的緩存在收到時(shí)已經(jīng)存在多久(在服務(wù)器中存在多久)
// 這個(gè)其實(shí)是根據(jù)請(qǐng)求頭中key為Age的值充边,與Cache-Control: max-age不同
// ageSeconds是從響應(yīng)頭中獲取的Age響應(yīng)頭對(duì)應(yīng)的秒數(shù)(本地緩存的響應(yīng)是由服務(wù)器
// 的緩存返回庸推,這個(gè)緩存在服務(wù)器存在的時(shí)間)
// ageSeconds與上一步的計(jì)算結(jié)果apparentReceivedAge的最大值為收到響應(yīng)時(shí),
// 這個(gè)響應(yīng)數(shù)據(jù)已經(jīng)存在多久浇冰。
// 這里這樣做贬媒,其實(shí)可能是服務(wù)器剛發(fā)出本響應(yīng)的時(shí)候創(chuàng)建的緩存,那么age的時(shí)間
// 可能就會(huì)小于客戶端接收到響應(yīng)的時(shí)間-服務(wù)器發(fā)出響應(yīng)的時(shí)間的差值
long receivedAge = ageSeconds != -1
? Math.max(apparentReceivedAge, SECONDS.toMillis(ageSeconds))
: apparentReceivedAge;
// responseDuration是緩存對(duì)應(yīng)的請(qǐng)求肘习,在發(fā)送請(qǐng)求與接收請(qǐng)求之間的時(shí)間差
long responseDuration = receivedResponseMillis - sentRequestMillis;
// 是這個(gè)緩存接收到的時(shí)間到現(xiàn)在的一個(gè)時(shí)間差
long residentDuration = nowMillis - receivedResponseMillis;
// 緩存在服務(wù)器已經(jīng)存在的時(shí)間+客戶端接收請(qǐng)求與發(fā)送請(qǐng)求的時(shí)間差+
// 接收到響應(yīng)緩存到現(xiàn)在的時(shí)間差
// 本次請(qǐng)求去獲取緩存际乘,這個(gè)緩存是上一次請(qǐng)求保存的
return receivedAge + responseDuration + residentDuration;
}
緩存新鮮度:即這個(gè)響應(yīng)有效緩存的時(shí)長(zhǎng),即freshMillis
緩存新鮮度(有效時(shí)長(zhǎng))的判斷會(huì)有多種情況漂佩,按優(yōu)先級(jí)排列如下:
- 緩存響應(yīng)包含Cache-Control: max-age=[秒]資源最大有效時(shí)間
- 緩存響應(yīng)包含Expires: 時(shí)間脖含,則通過(guò)Date或接收該響應(yīng)時(shí)間計(jì)算資源有效時(shí)間
- 緩存響應(yīng)包含Last-Modified: 時(shí)間,則通過(guò)Date或發(fā)送該響應(yīng)對(duì)應(yīng)請(qǐng)求的時(shí)間計(jì)算資源有效時(shí)間仅仆;并且根據(jù)建議以及在FireFox瀏覽器的實(shí)現(xiàn)器赞,使用得到結(jié)果的10%來(lái)作為資源的有效時(shí)間
private long computeFreshnessLifetime() {
CacheControl responseCaching = cacheResponse.cacheControl();
// 如果資源最大有效時(shí)間存在,則直接返回該值作為緩存新鮮度
if (responseCaching.maxAgeSeconds() != -1) {
return SECONDS.toMillis(responseCaching.maxAgeSeconds());
} else if (expires != null) {
// expires是數(shù)據(jù)到期時(shí)間
// servedDate是從緩存中獲得Data響應(yīng)頭對(duì)應(yīng)的時(shí)間(服務(wù)器發(fā)出本響應(yīng)的時(shí)間)
// receivedResponseMillis為本次服務(wù)器響應(yīng)對(duì)應(yīng)的客戶端發(fā)出請(qǐng)求的時(shí)間
// (這個(gè)應(yīng)該是客戶端接收到響應(yīng)的時(shí)間)
long servedMillis = servedDate != null
? servedDate.getTime()
: receivedResponseMillis;
// 計(jì)算差值墓拜,即為從接收到緩存到數(shù)據(jù)到期還有多久
long delta = expires.getTime() - servedMillis;
return delta > 0 ? delta : 0;
} else if (lastModified != null
&& cacheResponse.request().url().query() == null) {
// As recommended by the HTTP RFC and implemented in Firefox, the
// max age of a document should be defaulted to 10% of the
// document's age at the time it was served. Default expiration
// dates aren't used for URIs containing a query.
long servedMillis = servedDate != null
? servedDate.getTime()
: sentRequestMillis;
long delta = servedMillis - lastModified.getTime();
return delta > 0 ? (delta / 10) : 0;
}
return 0;
}
緩存最小新鮮度:請(qǐng)求認(rèn)為的緩存有效時(shí)間港柜,即minFreshMillis。假設(shè)緩存本身的新鮮度為100毫秒咳榜,而緩存最小新鮮度為10毫秒夏醉,那么緩存真正的有效時(shí)間為90毫秒。
過(guò)期后繼續(xù)使用時(shí)長(zhǎng):即超過(guò)緩存有效時(shí)間之后涌韩,還可以使用的時(shí)長(zhǎng)畔柔,即在這個(gè)時(shí)間內(nèi),依然可以使用緩存臣樱,即maxStaleMillis靶擦,也就是請(qǐng)求頭中的Cache-Control: max-state=[秒]緩存過(guò)期后仍然有效的時(shí)長(zhǎng)
// 第六步:響應(yīng)的緩存是否有效
// 6.1:獲得緩存的響應(yīng)從創(chuàng)建到現(xiàn)在的時(shí)間
long ageMillis = cacheResponseAge();
// 6.2:獲取這個(gè)響應(yīng)有效緩存時(shí)長(zhǎng)(緩存有效時(shí)間)與minFreshMillis的區(qū)別
// 其實(shí)就是minFreshMillis是請(qǐng)求認(rèn)為的緩存有效時(shí)間
long freshMillis = computeFreshnessLifetime();
// 如果請(qǐng)求中指定了max-age表示指定了能拿的緩存有效時(shí)長(zhǎng)腮考,就需要總和響應(yīng)
// 有效緩存時(shí)長(zhǎng)與請(qǐng)求能拿緩存的時(shí)長(zhǎng),獲得最小能夠使用響應(yīng)緩存的時(shí)長(zhǎng)
// max-age是資源最大有效時(shí)間
if (requestCaching.maxAgeSeconds() != -1) {
freshMillis = Math.min(freshMillis, SECONDS.toMillis(requestCaching.maxAgeSeconds()));
}
// 6.3:請(qǐng)求包含Cache-control: min-fresh=[秒] 能夠使用還未過(guò)指定時(shí)間
// 的緩存(用戶請(qǐng)求認(rèn)為的緩存有效時(shí)間玄捕,最小新鮮度)
long minFreshMillis = 0;
if (requestCaching.minFreshSeconds() != -1) {
minFreshMillis = SECONDS.toMillis(requestCaching.minFreshSeconds());
}
// 6.4
// 6.4.1:Cache-Control:must-revalidate 可緩存但是必須再向服務(wù)器進(jìn)行確認(rèn)
// 但是不可以使用過(guò)期資源
// 6.4.2:Cache-Control:max-state=[秒] 緩存過(guò)期后還能使用指定的時(shí)長(zhǎng)踩蔚,
// 如果未指定多少秒,則表示無(wú)論過(guò)期多長(zhǎng)時(shí)間都可以枚粘;如果指定了馅闽,則只要是
// 指定時(shí)間內(nèi)就能使用緩存
// 如果前者不滿足,則自動(dòng)忽略后者馍迄。只有不是必須向服務(wù)器進(jìn)行確認(rèn)的情況下
// 才會(huì)判斷緩存的過(guò)期時(shí)間
long maxStaleMillis = 0;
if (!responseCaching.mustRevalidate() && requestCaching.maxStaleSeconds() != -1) {
maxStaleMillis = SECONDS.toMillis(requestCaching.maxStaleSeconds());
}
// 6.5:不需要與服務(wù)器驗(yàn)證有效性 && 獲得緩存的響應(yīng)從創(chuàng)建到現(xiàn)在的時(shí)間 +
// 請(qǐng)求認(rèn)為的緩存有效時(shí)間(最小新鮮度) 小于 緩存有效時(shí)間 + 過(guò)期后還可以使用的時(shí)間
// 如果滿足條件福也,則允許使用緩存
if (!responseCaching.noCache() && ageMillis + minFreshMillis < freshMillis + maxStaleMillis) {
Response.Builder builder = cacheResponse.newBuilder();
// 如果緩存的響應(yīng)從創(chuàng)建到現(xiàn)在的時(shí)間 + 請(qǐng)求認(rèn)為的緩存有效時(shí)長(zhǎng)
// 小于 緩存有效時(shí)間,這樣的情況就是已經(jīng)過(guò)期攀圈,但是沒有超過(guò)過(guò)期后繼續(xù)
// 使用時(shí)長(zhǎng)暴凑,還是可以繼續(xù)使用,添加相應(yīng)的頭部字段
if (ageMillis + minFreshMillis >= freshMillis) {
builder.addHeader("Warning", "110 HttpURLConnection \"Response is stale\"");
}
// 如果緩存已經(jīng)過(guò)期一天量承,并且響應(yīng)中沒有設(shè)置過(guò)期時(shí)間也需要添加警告
long oneDayMillis = 24 * 60 * 60 * 1000L;
if (ageMillis > oneDayMillis && isFreshnessLifetimeHeuristic()) {
builder.addHeader("Warning", "113 HttpURLConnection \"Heuristic expiration\"");
}
return new CacheStrategy(null, builder.build());
}
看這部分源碼搬设,前面的4個(gè)小步驟,是計(jì)算對(duì)應(yīng)的時(shí)間撕捍,即緩存存活時(shí)間拿穴、緩存新鮮度、緩存最小新鮮度忧风、過(guò)期后依然可以使用緩存的時(shí)間默色。
(7)緩存過(guò)期處理
如果前面六步中,并沒有使用緩存狮腿,也沒有在之前進(jìn)行網(wǎng)絡(luò)請(qǐng)求腿宰,那么說(shuō)明緩存存在,但是緩存不可用缘厢,即本地緩存過(guò)期吃度。那么就需要判斷是否etag和lastModified,首先判斷Etag標(biāo)簽贴硫,將Etag標(biāo)簽的作為value椿每,然后以If-None-Match作為key,添加到請(qǐng)求頭中英遭;如果Etag為null间护,則考慮lastModified,將最后修改時(shí)間作為value挖诸,然后以If-Modified-Since作為key汁尺,添加到請(qǐng)求頭中;這樣做的目的是因?yàn)楸镜鼐彺嬉呀?jīng)過(guò)期多律,所以交給服務(wù)器來(lái)做比較痴突,如果服務(wù)器返回了304搂蜓,說(shuō)明是使用了服務(wù)器的緩存,則框架自動(dòng)更新本地緩存苞也。
(8)總結(jié)
1洛勉、如果從緩存獲取的Response是null,那就需要使用網(wǎng)絡(luò)請(qǐng)求獲取響應(yīng)如迟;
2、如果是Https請(qǐng)求攻走,但是又丟失了握手信息殷勘,那也不能使用緩存,需要進(jìn)行網(wǎng)絡(luò)請(qǐng)求昔搂;
3玲销、如果判斷響應(yīng)碼不能緩存且響應(yīng)頭有no-store標(biāo)識(shí),那就需要進(jìn)行網(wǎng)絡(luò)請(qǐng)求摘符;
這里需要特定的響應(yīng)碼贤斜,并不是所有的響應(yīng)碼都可以在沒有no-store的情況下去使用緩存
并且302和307還需要有特定的響應(yīng)頭配置,即Expires:時(shí)間(服務(wù)器返回給客戶端的數(shù)據(jù)到期時(shí)間)逛裤,
Cache-Control:max-age資源最大有效時(shí)間瘩绒,Cache-Control: public或者private
可緩存對(duì)象
4、如果請(qǐng)求頭有no-cache標(biāo)識(shí)或者有If-Modified-Since/If-None-Match带族,那么需要進(jìn)行網(wǎng)絡(luò)請(qǐng)求锁荔;
5、如果響應(yīng)頭沒有no-cache標(biāo)識(shí)蝙砌,且緩存時(shí)間沒有超過(guò)極限時(shí)間阳堕,那么可以使用緩存,不需要進(jìn)行網(wǎng)絡(luò)請(qǐng)求择克;
6恬总、如果緩存過(guò)期了,判斷響應(yīng)頭是否設(shè)置Etag/Last-Modified/Date肚邢,沒有那就直接使用網(wǎng)絡(luò)請(qǐng)求否則需要考慮服務(wù)器返回304壹堰;
并且,只要需要進(jìn)行網(wǎng)絡(luò)
四道偷、連接攔截器
連接攔截器主要做的事情有以下幾件:
(1)獲取對(duì)應(yīng)的發(fā)射器缀旁、Request和RealInterceptorChain
(2)在Transmitter.newExchange()調(diào)用ExchangeFinder.find方法,目的是為了找到RealConnection對(duì)象勺鸦,查找RealConnection的過(guò)程并巍,首先是查找發(fā)射器的現(xiàn)有連接是否存在,如果存在换途,則直接使用懊渡,如果不存在則從連接池中查找刽射,如果連接池中也不存在,則會(huì)創(chuàng)建剃执。這個(gè)過(guò)程中誓禁,總共查詢了三次連接池,第一次其實(shí)就是普通的查詢肾档,即路由集合傳入的是null摹恰,多路復(fù)用也是傳的false;第二次連接池查詢是基于多路由怒见,路由集合部分傳入了路由集合俗慈;在第二次連接池中查詢沒有找到可用連接之后,才會(huì)去創(chuàng)建一個(gè)新的連接遣耍,并且與服務(wù)器進(jìn)行握手闺阱,握手之后,又會(huì)進(jìn)行第三次查詢連接池舵变,第三次查詢是基于多路復(fù)用情況下進(jìn)行的酣溃。
(3)查詢到haelthy connection之后,通過(guò)RealConnection封裝OkHttpClient和鏈對(duì)象纪隙,根據(jù)是Http/2還是Http/1x創(chuàng)建不同的ExchangeCodec實(shí)現(xiàn)類赊豌,一般是Http1ExchangeCodec
(4)封裝Exchange對(duì)象
在這里涉及到一些相關(guān)的類:
RouteDataBase:這是一個(gè)關(guān)于路由信息的白名單和黑名單類,處于黑名單的路由信息會(huì)被避免不必要的嘗試瘫拣;該類是在RealConnectionPool中被使用亿絮;
RealConnecton:Connect子類,主要實(shí)現(xiàn)連接的建立等工作麸拄;
ConnectionPool:連接池派昧,實(shí)現(xiàn)連接的復(fù)用;
Http1ExchangeCodec:可用于發(fā)送HTTP / 1.1消息的套接字連接拢切;
Http2ExchangeCodec:使用HTTP / 2幀編碼請(qǐng)求和響應(yīng)蒂萎。
(1)ConnectionInterceptor
ConnectInterceptor連接攔截器,打開與目標(biāo)服務(wù)器的連接淮椰,并執(zhí)行下一個(gè)攔截器五慈。
public final class ConnectInterceptor implements Interceptor {
public final OkHttpClient client;
public ConnectInterceptor(OkHttpClient client) {
this.client = client;
}
@Override public Response intercept(Chain chain) throws IOException {
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Request request = realChain.request();
// Transmitter對(duì)象,是在RealCall中初始化創(chuàng)建的主穗,在Transmitter中就會(huì)初始化創(chuàng)建ConnectionPool
// 而ConnectionPool其實(shí)比較類似裝飾者模式泻拦,封裝RealConnectionPool
Transmitter transmitter = realChain.transmitter();
// 我們需要網(wǎng)絡(luò)來(lái)滿足這個(gè)請(qǐng)求『雒剑可能是為了驗(yàn)證一個(gè)條件GET請(qǐng)求(緩存驗(yàn)證等)争拐。
boolean doExtensiveHealthChecks = !request.method().equals("GET");
// 這個(gè)Exchange類,其實(shí)就是用于發(fā)送單個(gè)Http請(qǐng)求和一個(gè)響應(yīng)對(duì)晦雨,
// 在Exchange中會(huì)處理實(shí)際的I/O(ExchangeCodec)上分層連接管理和事件架曹。
// 所以要封裝Exchange也需要依賴于Transmitter發(fā)射器隘冲,所以尋找到的連接RealConnection
// 也需要保存在Transmitter中。
// 在3.14的源碼中绑雄,Transmitter的工作替換了StreamAllocation
Exchange exchange = transmitter.newExchange(chain, doExtensiveHealthChecks);
return realChain.proceed(request, transmitter, exchange);
}
}
ConnectInterceptor的代碼簡(jiǎn)單展辞,主要是因?yàn)橹饕倪壿嫸急环庋b到了其他類中。
首先我們看到的万牺,在這里依賴于Transmitter這個(gè)連接發(fā)射器罗珍,調(diào)用newExchange方法,其內(nèi)部就是將RealInterceptorChain對(duì)象和OkHttpClient對(duì)象封裝成Http1ExchangeCodec脚粟,而其內(nèi)部主要是先通過(guò)ExchangeFinder尋找一個(gè)有效的與請(qǐng)求主機(jī)的連接靡砌,通過(guò)調(diào)用ExchangeFinder.find方法
(2)Transmitter.newExchange()
Transsmitter.newExchange方法,其實(shí)就是封裝一個(gè)Exchange交換器珊楼,用來(lái)在下一個(gè)攔截器中攜帶最新的Request和Response
Exchange newExchange(Interceptor.Chain chain, boolean doExtensiveHealthChecks) {
synchronized (connectionPool) {
if (noMoreExchanges) {
throw new IllegalStateException("released");
}
if (exchange != null) {
throw new IllegalStateException("cannot make a new request because the previous response "
+ "is still open: please call response.close()");
}
}
// 這里就是尋找一個(gè)可用的連接,封裝一個(gè)對(duì)應(yīng)的Http版本的套接字連接
ExchangeCodec codec = exchangeFinder.find(client, chain, doExtensiveHealthChecks);
Exchange result = new Exchange(this, call, eventListener, exchangeFinder, codec);
synchronized (connectionPool) {
this.exchange = result;
this.exchangeRequestDone = false;
this.exchangeResponseDone = false;
return result;
}
}
(3)ExchangeFinder.find
該方法其實(shí)就是封裝ExchangeCodec對(duì)象度液,ExchangeCodec主要是用來(lái)編碼Http請(qǐng)求厕宗,并且對(duì)Http響應(yīng)進(jìn)行解碼的。在CallServerInterceptor攔截器中堕担,會(huì)多次調(diào)用到Exchange對(duì)象已慢,而Exchange對(duì)象中的很多方法都是通過(guò)ExchangeCodec來(lái)實(shí)現(xiàn)。
public ExchangeCodec find(
OkHttpClient client, Interceptor.Chain chain, boolean doExtensiveHealthChecks) {
int connectTimeout = chain.connectTimeoutMillis();
int readTimeout = chain.readTimeoutMillis();
int writeTimeout = chain.writeTimeoutMillis();
int pingIntervalMillis = client.pingIntervalMillis();
boolean connectionRetryEnabled = client.retryOnConnectionFailure();
try {
// 這里通過(guò)發(fā)射器查詢對(duì)應(yīng)的socket連接池中是否存在有效的連接霹购,如果存在則獲取
// 如果獲取到的是一個(gè)全新的連接佑惠,則不需要進(jìn)行是否healthy的檢查
// 否則需要進(jìn)行檢查
RealConnection resultConnection = findHealthyConnection(connectTimeout, readTimeout,
writeTimeout, pingIntervalMillis, connectionRetryEnabled, doExtensiveHealthChecks);
return resultConnection.newCodec(client, chain);
} catch (RouteException e) {
trackFailure();
throw e;
} catch (IOException e) {
trackFailure();
throw new RouteException(e);
}
}
在調(diào)用findHealthyConnection方法中,會(huì)調(diào)用到findConnection方法膜楷,在findConnection方法中會(huì)調(diào)用到RealConnectionPool.transmitterAcquirePooledConnection()赌厅,該方法的主要作用就是為嘗試為請(qǐng)求獲取對(duì)應(yīng)的連接特愿。并且將對(duì)應(yīng)的連接保存到對(duì)應(yīng)的發(fā)射器Transmitter中勾缭。
(4)ExchangeFinder.findHealthyConnection()
該方法的主要目的就是查找到一個(gè)健康可用的連接俩由,用于請(qǐng)求服務(wù)器。在findHealthyConnection方法中采驻,內(nèi)部其實(shí)就是調(diào)用了findConnection方法
private RealConnection findConnection(int connectTimeout, int readTimeout, int writeTimeout,
int pingIntervalMillis, boolean connectionRetryEnabled) throws IOException {
boolean foundPooledConnection = false;
RealConnection result = null;
Route selectedRoute = null;
RealConnection releasedConnection;
Socket toClose;
synchronized (connectionPool) {
// 請(qǐng)求已被取消
if (transmitter.isCanceled()) throw new IOException("Canceled");
hasStreamFailure = false; // This is a fresh attempt.
// Attempt to use an already-allocated connection. We need to be careful here because our
// already-allocated connection may have been restricted from creating new exchanges.
// 嘗試獲取已經(jīng)創(chuàng)建并且分配的連接审胚,已經(jīng)創(chuàng)建過(guò)的連接可能已經(jīng)被
// 限制創(chuàng)建新的流
releasedConnection = transmitter.connection;
// 如果已經(jīng)創(chuàng)建過(guò)的連接已經(jīng)被限制創(chuàng)建新的流匈勋,就釋放該連接
// (releaseConnectionNoEvents中會(huì)把該連接置空,并返回該連接的socket已關(guān)閉)
// RealConnection中的noNewExchanges則說(shuō)明無(wú)法在此連接上建立新的Exchange
// 此時(shí)就調(diào)用releaseConnectionNoEvents釋放連接資源膳叨,返回等待關(guān)閉的Socket套接字
// 每個(gè)Transmitter中都會(huì)有一個(gè)RealConnection洽洁,如果不可用,則釋放該RealConnection中資源
// 并且把這個(gè)RealConnection中對(duì)應(yīng)的Socket返回用于關(guān)閉連接通道
toClose = transmitter.connection != null && transmitter.connection.noNewExchanges
? transmitter.releaseConnectionNoEvents()
: null;
// 已經(jīng)創(chuàng)建過(guò)的連接還能使用菲嘴,就直接使用
if (transmitter.connection != null) {
// We had an already-allocated connection and it's good.
result = transmitter.connection;
// 這個(gè)為null饿自,用于說(shuō)明該連接是有效的
releasedConnection = null;
}
// 如果已經(jīng)創(chuàng)建過(guò)的連接不能使用
if (result == null) {
// Attempt to get a connection from the pool.
// TODO:第一次嘗試從連接池中查詢可用的連接,如果找到可用的連接龄坪,則會(huì)先分配給發(fā)射器
if (connectionPool.transmitterAcquirePooledConnection(address, transmitter, null, false)) {
// 從連接池中找到可用的連接昭雌,因?yàn)橐呀?jīng)被優(yōu)先賦值給了發(fā)射器transmitter.connection
foundPooledConnection = true;
result = transmitter.connection;
} else if (nextRouteToTry != null) {
selectedRoute = nextRouteToTry;
nextRouteToTry = null;
} else if (retryCurrentRoute()) {
selectedRoute = transmitter.connection.route();
}
}
}
closeQuietly(toClose);
if (releasedConnection != null) {
eventListener.connectionReleased(call, releasedConnection);
}
if (foundPooledConnection) {
eventListener.connectionAcquired(call, result);
}
if (result != null) {
// 經(jīng)過(guò)查詢已經(jīng)分配的連接吊履、連接池兩個(gè)過(guò)程之后找到可用的連接
// 直接返回該連接
return result;
}
// 判斷是否需要路由選擇(多IP操作的情況下)
boolean newRouteSelection = false;
// 第一次連接池中沒有查詢到可用的連接的時(shí)候当叭,
// 則在進(jìn)行第二次連接池查詢之前沧烈,判斷是否需要路由選擇冬阳,以便進(jìn)行通過(guò)路由集合查詢連接池
// 條件:已經(jīng)選擇的路由為null并且(路由選擇器中對(duì)應(yīng)的已選擇的路由集合為null或者沒有下一個(gè))
if (selectedRoute == null && (routeSelection == null || !routeSelection.hasNext())) {
newRouteSelection = true;
routeSelection = routeSelector.next();
}
List<Route> routes = null;
synchronized (connectionPool) {
if (transmitter.isCanceled()) throw new IOException("Canceled");
// 如果有下一個(gè)路由
if (newRouteSelection) {
// 第二次嘗試從連接池中查詢可用連接
// 此時(shí)與上一次不同的是這里傳入了路由集合
routes = routeSelection.getAll();
if (connectionPool.transmitterAcquirePooledConnection(
address, transmitter, routes, false)) {
// 從連接池中找到可用連接
foundPooledConnection = true;
result = transmitter.connection;
}
}
// 如果連接池中沒有可用連接
if (!foundPooledConnection) {
if (selectedRoute == null) {
selectedRoute = routeSelection.next();
}
// 創(chuàng)建一個(gè)新的連接,交由下面進(jìn)行socket連接
result = new RealConnection(connectionPool, selectedRoute);
connectingConnection = result;
}
}
// 這里是第二次從連接池中查詢到了可用連接之后
// 直接返回炬搭,如果第二次從連接池中并沒有找到可用連接充尉,創(chuàng)建了一個(gè)新的連接
// 則這里不會(huì)返回
if (foundPooledConnection) {
eventListener.connectionAcquired(call, result);
return result;
}
// 如果第二次查詢連接池沒有找到可用連接,則把新創(chuàng)建的連接進(jìn)行TCP+TLS握手
// 與服務(wù)端建立連接苛预,這是一個(gè)阻塞操作
// 這里其實(shí)就會(huì)根據(jù)連接池中查詢不到可用連接,而創(chuàng)建一個(gè)新的socket套接字
// 在RealConnection的connect方法中調(diào)用connectSocket方法初始化rawSocket
// 然后接著調(diào)用establishProtocol將rawSocket賦值給socket
// Do TCP + TLS handshakes。連接Server
// TODO: 在這里進(jìn)行TCP連接丘薛,TCP連接開始之后,進(jìn)行TLS安全連接過(guò)程,然后才會(huì)結(jié)束TCP連接
result.connect(connectTimeout, readTimeout, writeTimeout, pingIntervalMillis,
connectionRetryEnabled, call, eventListener);
// 將路由信息添加到RouteDatabase
connectionPool.routeDatabase.connected(result.route());
Socket socket = null;
synchronized (connectionPool) {
connectingConnection = null;
// 最后一次嘗試從連接池中獲取連接,最后一個(gè)參數(shù)為true锅知,即要求多路復(fù)用
// 為了保證多路復(fù)用可训,會(huì)再次確認(rèn)連接池中此時(shí)是否有同樣的連接
// 這里的多路復(fù)用是為了確保http2的連接多路復(fù)用功能
// 即在創(chuàng)建一個(gè)新的連接的時(shí)候,判斷是否是Http2
if (connectionPool.transmitterAcquirePooledConnection(address, transmitter, routes, true)) {
// 如果獲取到,就關(guān)閉在創(chuàng)建里的連接胯努,返回從連接池中獲取的連接
result.noNewExchanges = true;
socket = result.socket();
result = transmitter.connection;
// 剛剛連接成功的路由忘朝,因?yàn)槲覀儚倪B接池中找到可用連接而變成不健康的
// 我們可以保存用于下次嘗試的路由
nextRouteToTry = selectedRoute;
} else {
// 最后一次嘗試從連接池中獲取晦墙,沒有找到可用的連接
// 則將連接添加到連接池中
connectionPool.put(result);
transmitter.acquireConnectionNoEvents(result);
}
}
closeQuietly(socket);
eventListener.connectionAcquired(call, result);
return result;
}
在OkHttp3中独郎,RealConnection默認(rèn)會(huì)保存5個(gè)空閑連接,保持5分鐘反粥。這些空閑連接如果5分鐘內(nèi)沒有被使用,則會(huì)從連接池中移除。而OkHttp中的連接池尾组,其實(shí)是RealConnectionPool奏属,而ConnectionPool其實(shí)可以認(rèn)為是一個(gè)裝飾類,封裝RealConnectionPool的功能咆耿。
public ConnectionPool() {
this(5, 5, TimeUnit.MINUTES);
}
public ConnectionPool(int maxIdleConnections, long keepAliveDuration, TimeUnit timeUnit) {
this.delegate = new RealConnectionPool(maxIdleConnections, keepAliveDuration, timeUnit);
}
(5)RealConnectionPool.transmitterAcquirePooledConnection()
嘗試從連接池中查詢可用的連接,如果找到可用的連接椭盏,則會(huì)先分配給發(fā)射器。這里就是從連接池中取出連接
boolean transmitterAcquirePooledConnection(Address address, Transmitter transmitter,
@Nullable List<Route> routes, boolean requireMultiplexed) {
assert (Thread.holdsLock(this));
for (RealConnection connection : connections) {
if (requireMultiplexed && !connection.isMultiplexed()) continue;
if (!connection.isEligible(address, routes)) continue;
// 尋找到符合要求的允許復(fù)用的連接,保存到Transmitter發(fā)射器中
transmitter.acquireConnectionNoEvents(connection);
return true;
}
return false;
}
(6)RealConnectionPool.cleanup
線程池的cleanup方法准浴,是在RealConnectionPool中定義的一個(gè)Runnable對(duì)象cleanupRunnable中的run方法調(diào)動(dòng)今野,是一個(gè)無(wú)限循環(huán)調(diào)用。在cleanup中蛆楞,會(huì)遍歷所有的連接矛纹,找到空閑連接數(shù),并且找到空閑時(shí)間最久的那個(gè)連接以及空閑時(shí)間采够,然后判斷連接池中空閑連接數(shù)是否大于5或者空閑最久的是否超過(guò)5分鐘逝薪,如果滿足其中一個(gè)則執(zhí)行remove操作
private final Runnable cleanupRunnable = () -> {
while (true) {
long waitNanos = cleanup(System.nanoTime());
if (waitNanos == -1) return;
if (waitNanos > 0) {
long waitMillis = waitNanos / 1000000L;
waitNanos -= (waitMillis * 1000000L);
synchronized (RealConnectionPool.this) {
try {
RealConnectionPool.this.wait(waitMillis, (int) waitNanos);
} catch (InterruptedException ignored) {
}
}
}
}
};
往連接池中put連接,就會(huì)通過(guò)一個(gè)線程池執(zhí)行連接池的清理任務(wù)
void put(RealConnection connection) {
assert (Thread.holdsLock(this));
if (!cleanupRunning) {
cleanupRunning = true;
executor.execute(cleanupRunnable);
}
connections.add(connection);
}
long cleanup(long now) {
int inUseConnectionCount = 0;
int idleConnectionCount = 0;
RealConnection longestIdleConnection = null;
long longestIdleDurationNs = Long.MIN_VALUE;
// Find either a connection to evict, or the time that the next eviction is due.
synchronized (this) {
for (Iterator<RealConnection> i = connections.iterator(); i.hasNext(); ) {
RealConnection connection = i.next();
// If the connection is in use, keep searching.
if (pruneAndGetAllocationCount(connection, now) > 0) {
// 連接池中處于使用狀態(tài)的連接數(shù)
inUseConnectionCount++;
continue;
}
// 處于空閑狀態(tài)的連接數(shù)
idleConnectionCount++;
// 找到空閑時(shí)間最久的那個(gè)連接
long idleDurationNs = now - connection.idleAtNanos;
if (idleDurationNs > longestIdleDurationNs) {
longestIdleDurationNs = idleDurationNs;
longestIdleConnection = connection;
}
}
// 如果空閑時(shí)間大于keepAliveDurationNs(默認(rèn)5分鐘)
// 或者空閑的連接總數(shù)大于maxIdleConnections(默認(rèn)5個(gè))
// 執(zhí)行移除操作
if (longestIdleDurationNs >= this.keepAliveDurationNs
|| idleConnectionCount > this.maxIdleConnections) {
// We've found a connection to evict. Remove it from the list, then close it below (outside
// of the synchronized block).
connections.remove(longestIdleConnection);
} else if (idleConnectionCount > 0) {
// 空閑最久的那個(gè)連接的空閑時(shí)長(zhǎng)與keepAliveDurationNs的差值
return keepAliveDurationNs - longestIdleDurationNs;
} else if (inUseConnectionCount > 0) {
// All connections are in use. It'll be at least the keep alive duration 'til we run again.
return keepAliveDurationNs;
} else {
// No connections, idle or in use.
cleanupRunning = false;
return -1;
}
}
// 關(guān)閉需要移除的空閑連接的socket
closeQuietly(longestIdleConnection.socket());
// Cleanup again immediately.
return 0;
}
(7)RealConnection.newCodec
在尋找找有效的請(qǐng)求連接之后封豪,通過(guò)調(diào)用RealConnection的newCodec。即該方法是在ExchangeFinder.find方法中調(diào)用findHealthyConnection方法獲取有效連接之后雌续。
這里返回的是一個(gè)ExchangeCodec對(duì)象,而ExchangeCodec是一個(gè)接口鸽心,其實(shí)現(xiàn)類是Http1ExchangeCodec和Http2ExchangeCodec,Http2ExchangeCodec是用于Http/2版本的。
返回一個(gè)Http1ExchangeCodec
接著在發(fā)射器中,將其封裝成一個(gè)Exchange對(duì)象怠惶。
這個(gè)Exchange類,其實(shí)就是用于發(fā)送單個(gè)Http請(qǐng)求和一個(gè)響應(yīng)對(duì)轧拄,在Exchange中會(huì)處理實(shí)際的I/O(ExchangeCodec)上分層連接管理和事件俐末。
(8)RealConnection
// RealConnectionPool中緩存的是RealConnection對(duì)象
public final RealConnectionPool connectionPool;
private Socket socket;
RealConnectionPool
private final Deque<RealConnection> connections = new ArrayDeque<>();
在RealConnection中,封裝了Socket與一個(gè)Socket連接池。而isEligible方法,主要的目的是在從Socket連接池中獲取到對(duì)應(yīng)的有效連接的時(shí)候藐吮,判斷是否有資格處理針對(duì)該域名主機(jī)的該請(qǐng)求事件沐扳。
isEligible方法是在ExchangeFinder調(diào)用findConnection方法尋找有效連接的時(shí)候躯嫉,調(diào)用RealConnectionPool.transmitterAcquirePooledConnection方法的時(shí)候調(diào)用的戏阅。
boolean isEligible(Address address, @Nullable List<Route> routes) {
// 如果連接不接受新的流,則完成芭逝。這樣的情況一般有兩種胖翰,一種是達(dá)到最大并發(fā)流
// 或者是連接就不允許建立新的流切厘;如Http1.x正在使用的連接不能給其他人用
// (最大并發(fā)流為:1)或者連接被關(guān)閉萨咳,那么就不允許復(fù)用。
if (transmitters.size() >= allocationLimit || noNewExchanges) return false;
// DNS疫稿、代理培他、SSL證書舀凛、服務(wù)器域名奸晴、端口完全相同則可復(fù)用
// 如果上述條件都不滿足,在HTTP/2的某些場(chǎng)景下可能仍可復(fù)用
if (!Internal.instance.equalsNonHost(this.route.address(), address)) return false;
if (address.url().host().equals(this.route().address().url().host())) {
return true; // This connection is a perfect match.
}
// At this point we don't have a hostname match. But we still be able to carry the request if
// our connection coalescing requirements are met. See also:
// https://hpbn.co/optimizing-application-delivery/#eliminate-domain-sharding
// https://daniel.haxx.se/blog/2016/08/18/http2-connection-coalescing/
// 1. This connection must be HTTP/2.
if (http2Connection == null) return false;
// 2. The routes must share an IP address.
if (routes == null || !routeMatchesAny(routes)) return false;
// 3. This connection's server certificate's must cover the new host.
if (address.hostnameVerifier() != OkHostnameVerifier.INSTANCE) return false;
if (!supportsUrl(address.url())) return false;
// 4. Certificate pinning must match the host.
try {
address.certificatePinner().check(address.url().host(), handshake().peerCertificates());
} catch (SSLPeerUnverifiedException e) {
return false;
}
return true; // The caller's address can be carried by this connection.
}
在連接攔截器中的所有實(shí)現(xiàn)都是為了獲得一份與目標(biāo)服務(wù)器的連接译秦,在這個(gè)連接上進(jìn)行Http數(shù)據(jù)的收發(fā)射沟。
五、請(qǐng)求服務(wù)器攔截器
CallServerInterceptor通過(guò)封裝的Exchange中的ExchangeCodec對(duì)象(Http1ExchangeCodec)發(fā)出請(qǐng)求到服務(wù)器并且解析生成Response
- (1)封裝request壤玫,放在BufferedSink緩存流中
- (2)如果不是get請(qǐng)求或者不是head請(qǐng)求,且有request body著拭,則判斷請(qǐng)求頭中是否有Expect:100-continue岳锁,如果有宪肖,則封裝請(qǐng)求信息镰吆,優(yōu)先發(fā)送一次請(qǐng)求妙黍,得到響應(yīng)碼為100吼和,再發(fā)送請(qǐng)求體進(jìn)行請(qǐng)求
- (3)根據(jù)不同情況的responseBuilder是否為null,初始化responseBuilder
- (4)使用responseBuilder發(fā)起第一次請(qǐng)求,接收response
- (5)判斷response的code是否為100,如果是100,則進(jìn)行第二次請(qǐng)求抖拦,這次請(qǐng)求是真實(shí)的數(shù)據(jù)請(qǐng)求,如果不是100,則不進(jìn)行第二次請(qǐng)求
- (6)重新builder返回結(jié)果想诅,將response進(jìn)行重新封裝娘荡,將請(qǐng)求獲取到的響應(yīng)數(shù)據(jù)封裝成responseBody干旁,而不是之前的數(shù)據(jù)流的形式。
- (7)判斷是否關(guān)閉長(zhǎng)連接炮沐,并且處理無(wú)響應(yīng)體異常問(wèn)題
1.CallServerInterceptor.intercept()
@Override public Response intercept(Chain chain) throws IOException {
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Exchange exchange = realChain.exchange();
Request request = realChain.request();
long sentRequestMillis = System.currentTimeMillis();
// 調(diào)用Exchange.writeRequestHeaders争群,其內(nèi)部就是調(diào)用了ExchangeCodec
// 的writeRequestHeaders方法,將請(qǐng)求信息寫到緩存中(BufferedSink)央拖,
// 其實(shí)就是將請(qǐng)求信息轉(zhuǎn)成緩存流,使用BufferedSink來(lái)進(jìn)行緩存
// 這里其實(shí)就是OkHttp采用的Okio的方式
exchange.writeRequestHeaders(request);
boolean responseHeadersStarted = false;
Response.Builder responseBuilder = null;
// 這里整個(gè)請(qǐng)求都與一個(gè)請(qǐng)求頭有關(guān):Expect: 100-continue
// 這個(gè)請(qǐng)求頭代表了在發(fā)送請(qǐng)求體之前需要和服務(wù)器確定是否愿意接受客戶端發(fā)送的請(qǐng)求體鹉戚。
// 所以permitsRequestBody判斷為是否會(huì)攜帶請(qǐng)求體的方式(POST)鲜戒,
// 如果命中if,則會(huì)先給服務(wù)器發(fā)起一次查詢是否愿意接收請(qǐng)求體抹凳,這個(gè)時(shí)候如果
// 服務(wù)器愿意會(huì)響應(yīng)100(沒有響應(yīng)體遏餐,responseBuilder即為null)
// 直到返回為100-continue之后,才能夠繼續(xù)發(fā)送剩余請(qǐng)求數(shù)據(jù)
if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
// 如果請(qǐng)求希望帶上"Expect: 100-continue"赢底,則在發(fā)送請(qǐng)求之前失都,需要先
// 等待HTTP/1.1 100 Continue的響應(yīng)。如果沒有得到響應(yīng)幸冻,即responseBuilder=null
// 則返回得到的結(jié)果粹庞,并且不需要傳請(qǐng)求體
if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
// 真正調(diào)用請(qǐng)求的地方,通過(guò)flushRequest之后洽损,將請(qǐng)求信息發(fā)送給服務(wù)器
exchange.flushRequest();
responseHeadersStarted = true;
// 注冊(cè)請(qǐng)求監(jiān)聽回調(diào)
exchange.responseHeadersStart();
// 獲取Expect: 100-continue的請(qǐng)求頭的請(qǐng)求之后的responseBuilder
// 如果服務(wù)器不允許接收請(qǐng)求體庞溜,則這里的responseBuilder不為null
// 如果服務(wù)器允許接收請(qǐng)求,則這里的responseBuilder為null碑定,code為100
// 返回為null流码,是因?yàn)閭魅氲膮?shù)為true,導(dǎo)致直接return null;
responseBuilder = exchange.readResponseHeaders(true);
}
if (responseBuilder == null) {
// 是否是雙工請(qǐng)求
if (request.body().isDuplex()) {
exchange.flushRequest();
BufferedSink bufferedRequestBody = Okio.buffer(
exchange.createRequestBody(request, true));
request.body().writeTo(bufferedRequestBody);
} else {
// Write the request body if the "Expect: 100-continue" expectation was met.
// 寫入請(qǐng)求頭中帶有Expect: 100-continue的第一次請(qǐng)求的響應(yīng)碼為100時(shí)延刘,向請(qǐng)求中寫入請(qǐng)求體漫试,進(jìn)行二次請(qǐng)求
BufferedSink bufferedRequestBody = Okio.buffer(
exchange.createRequestBody(request, false));
request.body().writeTo(bufferedRequestBody);
bufferedRequestBody.close();
}
} else {
exchange.noRequestBody();
if (!exchange.connection().isMultiplexed()) {
// If the "Expect: 100-continue" expectation wasn't met, prevent the HTTP/1 connection
// from being reused. Otherwise we're still obligated to transmit the request body to
// leave the connection in a consistent state.
exchange.noNewExchangesOnConnection();
}
}
} else {
// 如果服務(wù)器不同意接收請(qǐng)求體,那么需要標(biāo)記該鏈接不能再被復(fù)用
// 則調(diào)用Exchange.noRequestBody()碘赖,會(huì)清除Socket連接池中的鏈接
// 同時(shí)關(guān)閉相關(guān)的Socket鏈接驾荣。
exchange.noRequestBody();
}
if (request.body() == null || !request.body().isDuplex()) {
exchange.finishRequest();
}
// 如果POST請(qǐng)求沒有Expect: 100-continue或者是GET請(qǐng)求
// 則在這里注冊(cè)請(qǐng)求的Call的監(jiān)聽回調(diào)
if (!responseHeadersStarted) {
exchange.responseHeadersStart();
}
// 如果可以繼續(xù)進(jìn)行請(qǐng)求外构,則通過(guò)Exchange獲取responseBuilder用于獲取
// 服務(wù)器的請(qǐng)求返回Response
// 這個(gè)時(shí)候responseBuilder的情況為:
// 1.POST方式請(qǐng)求,請(qǐng)求頭中包含Expect秘车,服務(wù)器允許接收請(qǐng)求體典勇,
// 并且已經(jīng)發(fā)出了請(qǐng)求體,responseBuilder為null
// 2.POST方式請(qǐng)求叮趴,請(qǐng)求體中包含Expect割笙,服務(wù)器不允許接收請(qǐng)求體,
// responseBuilder不為null
// 3.POST方式請(qǐng)求眯亦,未包含Expect伤溉,直接發(fā)出請(qǐng)求,responseBuilder為null
// 4.POST方式請(qǐng)求妻率,沒有請(qǐng)求體乱顾,responseBuilder為null
// 5.GET方式請(qǐng)求,responseBuilder為null
if (responseBuilder == null) {
// 獲取Response.Builder實(shí)例
// 這個(gè)實(shí)例并沒有發(fā)起真正的請(qǐng)求宫静,只是添加了readHeaders等配置信息
// 具體請(qǐng)求在下面走净,添加request,并且執(zhí)行build
responseBuilder = exchange.readResponseHeaders(false);
}
// 如果這個(gè)response不是Expect: 100-continue的響應(yīng)結(jié)果
// 這會(huì)是直接發(fā)出請(qǐng)求得到的結(jié)果孤里。
// request可能是請(qǐng)求頭中包含Expect: 100-continue的第一次請(qǐng)求伏伯,
// 那么就需要在第一次請(qǐng)求之后再進(jìn)行一次真實(shí)的數(shù)據(jù)請(qǐng)求,獲取真實(shí)的Response
// 也可能是沒有包含Expect: 100-continue的對(duì)服務(wù)器的直接請(qǐng)求
// 那么這次請(qǐng)求返回的Response就是真實(shí)的Response
// 獲取到真實(shí)的Response之后捌袜,需要對(duì)Response進(jìn)行數(shù)據(jù)封裝说搅,
// 因?yàn)榉祷氐捻憫?yīng)體其實(shí)還是類似于請(qǐng)求體封裝那樣的一種字符串形式的
Response response = responseBuilder
.request(request)
.handshake(exchange.connection().handshake())
.sentRequestAtMillis(sentRequestMillis)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
// 對(duì)應(yīng)上面5種請(qǐng)求,讀取響應(yīng)頭并且組成響應(yīng)Response虏等,注意:這個(gè)Response
// 沒有響應(yīng)體弄唧。同時(shí)需要注意的是,如果服務(wù)器接受Expect: 100-continue
// 這是不是意味著我們發(fā)起了兩次Request霍衫?那此時(shí)的響應(yīng)頭是第一次查詢服務(wù)器
// 是否支持接受請(qǐng)求體的候引,而不是真正的請(qǐng)求對(duì)應(yīng)的結(jié)果響應(yīng)
int code = response.code();
if (code == 100) {
// 如果響應(yīng)的code=100,這代表了請(qǐng)求Expect: 100-continue成功的響應(yīng)
// 需要馬上再次讀取一次響應(yīng)頭敦跌,這才是真正的請(qǐng)求對(duì)應(yīng)結(jié)果響應(yīng)頭
// 這次其實(shí)就是在服務(wù)器愿意客戶端發(fā)送請(qǐng)求之后
// 客戶端再一次對(duì)服務(wù)器進(jìn)行請(qǐng)求得到的response
response = exchange.readResponseHeaders(false)
.request(request)
.handshake(exchange.connection().handshake())
.sentRequestAtMillis(sentRequestMillis)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
code = response.code();
}
exchange.responseHeadersEnd(response);
// forWebSocket代表webSocket看的請(qǐng)求背伴,這里一般并不是,所以進(jìn)入else
// 在else中就是讀取響應(yīng)體數(shù)據(jù)峰髓。
if (forWebSocket && code == 101) {
// Connection is upgrading, but we need to ensure interceptors see a non-null response body.
response = response.newBuilder()
.body(Util.EMPTY_RESPONSE)
.build();
} else {
// 針對(duì)服務(wù)器返回的response進(jìn)行封裝傻寂。
response = response.newBuilder()
.body(exchange.openResponseBody(response))
.build();
}
// 然后判斷請(qǐng)求和服務(wù)器是不是都希望長(zhǎng)連接
// 一旦有一方指明close,那么就需要關(guān)閉socket携兵。
if ("close".equalsIgnoreCase(response.request().header("Connection"))
|| "close".equalsIgnoreCase(response.header("Connection"))) {
exchange.noNewExchangesOnConnection();
}
// 而如果服務(wù)器返回204/205
// 一般情況而言不會(huì)存在這些返回碼疾掰,但是一旦出現(xiàn)這意味著沒有響應(yīng)體,
// 但是解析到的響應(yīng)頭中包含Content-Length且不為0徐紧,這表示響應(yīng)體的數(shù)據(jù)
// 字節(jié)長(zhǎng)度静檬。此時(shí)出現(xiàn)了沖突炭懊,直接拋出協(xié)議異常。
if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
throw new ProtocolException(
"HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
}
return response;
}
2.Exchange.writeRequestHeaders()
緩存請(qǐng)求信息拂檩,將請(qǐng)求信息緩存到BufferedSink中侮腹。即Http1ExchangeCodec中的BufferedSink中
public void writeRequestHeaders(Request request) throws IOException {
try {
eventListener.requestHeadersStart(call);
codec.writeRequestHeaders(request);
eventListener.requestHeadersEnd(call, request);
} catch (IOException e) {
eventListener.requestFailed(call, e);
trackFailure(e);
throw e;
}
}
3.Http1Exchange.readResponseHeaders
在這里,如果傳入的expectContinue=true稻励,那么就會(huì)返回為null父阻,如果傳入的是false,就會(huì)返回responseBuilder實(shí)例望抽。
@Override public Response.Builder readResponseHeaders(boolean expectContinue) throws IOException {
if (state != STATE_OPEN_REQUEST_BODY && state != STATE_READ_RESPONSE_HEADERS) {
throw new IllegalStateException("state: " + state);
}
try {
StatusLine statusLine = StatusLine.parse(readHeaderLine());
Response.Builder responseBuilder = new Response.Builder()
.protocol(statusLine.protocol)
.code(statusLine.code)
.message(statusLine.message)
.headers(readHeaders());
if (expectContinue && statusLine.code == HTTP_CONTINUE) {
return null;
} else if (statusLine.code == HTTP_CONTINUE) {
state = STATE_READ_RESPONSE_HEADERS;
return responseBuilder;
}
state = STATE_OPEN_RESPONSE_BODY;
return responseBuilder;
} catch (EOFException e) {
// Provide more context if the server ends the stream before sending a response.
String address = "unknown";
if (realConnection != null) {
address = realConnection.route().address().url().redact();
}
throw new IOException("unexpected end of stream on "
+ address, e);
}
}