上一篇Okhttp主流程源碼淺析(1)分析到任務(wù)調(diào)度方面,接著把剩下的主流程分析.
當(dāng)一個(gè)任務(wù)被執(zhí)行起來,會(huì)調(diào)用getResponseWithInterceptorChain()
來獲取到響應(yīng)結(jié)果 response
//TODO: 責(zé)任鏈模式,攔截器鏈 執(zhí)行請求
//TODO: 拿到回調(diào)結(jié)果
Response response = getResponseWithInterceptorChain();
getResponseWithInterceptorChain()源碼:
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
//TODO 責(zé)任鏈
List<Interceptor> interceptors = new ArrayList<>();
interceptors.addAll(client.interceptors());
//TODO 處理重試與重定向
interceptors.add(retryAndFollowUpInterceptor);
//TODO 處理 配置請求頭等信息
interceptors.add(new BridgeInterceptor(client.cookieJar()));
//TODO 處理 緩存配置 根據(jù)條件(存在響應(yīng)緩存并被設(shè)置為不變的或者響應(yīng)在有效期內(nèi))返回緩存響應(yīng)
//TODO 設(shè)置請求頭
interceptors.add(new CacheInterceptor(client.internalCache()));
//TODO 連接服務(wù)器
interceptors.add(new ConnectInterceptor(client));
if (!forWebSocket) {
interceptors.addAll(client.networkInterceptors());
}
//TODO 執(zhí)行流操作(寫出請求體租幕、獲得響應(yīng)數(shù)據(jù))
//TODO 進(jìn)行http請求報(bào)文的封裝與請求報(bào)文的解析
interceptors.add(new CallServerInterceptor(forWebSocket));
Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
originalRequest, this, eventListener, client.connectTimeoutMillis(),
client.readTimeoutMillis(), client.writeTimeoutMillis());
return chain.proceed(originalRequest);
}
創(chuàng)建List<Interceptor> interceptors = new ArrayList<>()
集合來保存攔截器,平時(shí)我們自己給OkHttpClient添加的攔截器也是在這里處理.
例如添加log 攔截器:
//添加log攔截器
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.addInterceptor(interceptor);
這些攔截器保存在OkHttpClient實(shí)例里面,到這里會(huì)調(diào)用interceptors.addAll(client.interceptors())
把我們的攔截器先添加到集合里面,然后再添加一些默認(rèn)的攔截器來處理請求與響應(yīng)
責(zé)任鏈的攔截器集合內(nèi)容如下:
1.自定義攔截器
2.retryAndFollowUpInterceptor: 重試與重定向攔截器
3.BridgeInterceptor: 處理配置請求頭等信息
4.CacheInterceptor: 處理緩存信息
5.ConnectInterceptor: 連接服務(wù)器
6.CallServerInterceptor: http報(bào)文封裝與解析,與服務(wù)器執(zhí)行流操作
責(zé)任鏈調(diào)用順序圖:
調(diào)用順序:
當(dāng)發(fā)起一個(gè)請求,首先會(huì)進(jìn)入到自定義攔截器里面,然后再依次進(jìn)入okhttp默認(rèn)的各個(gè)攔截器里面,最終連接到服務(wù)器,進(jìn)行流的讀寫, 拿到服務(wù)器返回的響應(yīng)結(jié)果,再反過來,依次的回調(diào)到調(diào)用者.
在上面的getResponseWithInterceptorChain()方法里面,把攔截器添加完成之后,會(huì)執(zhí)行如下代碼:
Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
originalRequest, this, eventListener, client.connectTimeoutMillis(),
client.readTimeoutMillis(), client.writeTimeoutMillis());
return chain.proceed(originalRequest);
創(chuàng)建RealInterceptorChain realInterceptorChain = new RealInterceptorChain
,然后開始執(zhí)行責(zé)任鏈,調(diào)用chain.proceed(originalRequest)把請求傳入進(jìn)去,看下RealInterceptorChain的proceed方法
@Override public Response proceed(Request request) throws IOException {
return proceed(request, streamAllocation, httpCodec, connection);
}
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException {
//省略代碼
...
//TODO: 創(chuàng)建新的攔截鏈拙泽,鏈中的攔截器集合index+1
RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
writeTimeout);
//TODO: 執(zhí)行當(dāng)前的攔截器 默認(rèn)是:retryAndFollowUpInterceptor
Interceptor interceptor = interceptors.get(index);
Response response = interceptor.intercept(next);
//省略代碼
...
return response;
}
刪除了部分判斷的代碼,這里看重點(diǎn),在proceed()里面看到,會(huì)再創(chuàng)建一個(gè)新的對象RealInterceptorChain next = new RealInterceptorChain(...)并且把攔截器集合通過構(gòu)造方法傳入,還有一些其他信息.
注意: 這里的會(huì)把 index + 1再傳入進(jìn)去,下面會(huì)用到
然后再從攔截器集合里面拿到一個(gè)攔截器interceptors.get(index)
,并且去執(zhí)行這個(gè)攔截器的方法拿到響應(yīng)結(jié)果Response response = interceptor.intercept(next);
回到上面看下調(diào)用順序圖,如果我們有給okhttpClient加入自定義攔截器,這里就先調(diào)用自定義攔截器,否則就開始執(zhí)行第一個(gè)默認(rèn)的攔截器retryAndFollowUpInterceptor
看下retryAndFollowUpInterceptor.intercept(next)方法
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Call call = realChain.call();
EventListener eventListener = realChain.eventListener();
//TODO 核心 協(xié)調(diào)連接喘先、請求/響應(yīng)以及復(fù)用
StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
createAddress(request.url()), call, eventListener, callStackTrace);
this.streamAllocation = streamAllocation;
int followUpCount = 0;
Response priorResponse = null;
while (true) {
if (canceled) {
streamAllocation.release();
throw new IOException("Canceled");
}
Response response;
boolean releaseConnection = true;
try {
//TODO 執(zhí)行責(zé)任鏈 實(shí)際上就是下一個(gè)攔截器
response = realChain.proceed(request, streamAllocation, null, null);
releaseConnection = false;
} catch (RouteException e) {
} catch (IOException e) {
} finally {
}
...刪除部分代碼
return response;
}
}
這里會(huì)StreamAllocation streamAllocation = new StreamAllocation(...)
創(chuàng)建一個(gè)StreamAllocation對象,并且把連接池,和請求地址信息,call等等通過構(gòu)造傳入,這里只關(guān)心主流程,StreamAllocation的作用不說了
然后開了個(gè)while (true) {}
循環(huán),在里面會(huì)調(diào)用response = realChain.proceed(request, streamAllocation, null, null);
繼續(xù)執(zhí)行責(zé)任鏈的下一個(gè)攔截器,這個(gè)realChain就是上面retryAndFollowUpInterceptor.intercept(next)
傳入的這個(gè)next,就是上面提到的那個(gè)RealInterceptorChain對象,注意這個(gè)時(shí)候的index = 1然后繼續(xù)執(zhí)行proceed()方法
這里又回到了前面RealInterceptorChain.proceed()
@Override public Response proceed(Request request) throws IOException {
return proceed(request, streamAllocation, httpCodec, connection);
}
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException {
//省略代碼
...
//TODO: 創(chuàng)建新的攔截鏈,鏈中的攔截器集合index+1
RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
writeTimeout);
//TODO: 執(zhí)行當(dāng)前的攔截器 默認(rèn)是:retryAndFollowUpInterceptor
Interceptor interceptor = interceptors.get(index);
Response response = interceptor.intercept(next);
//省略代碼
...
return response;
}
這里的代碼有點(diǎn)繞,第一次看有點(diǎn)暈頭轉(zhuǎn)向的感覺~~
沒錯(cuò),這里又回到上面的地方,不過有兩點(diǎn)不同了
1.第一次進(jìn)來的時(shí)候index = 0,streamAllocation = null
2.這一次index = 1,streamAllocation剛剛被 new 出來
然后再次創(chuàng)建一個(gè)新的RealInterceptorChain對象,把信息傳入構(gòu)造.
注意: 這個(gè)時(shí)候 index = 1, 所以傳入next 里面的 index = 1+1
RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
writeTimeout);
然后再調(diào)用Interceptor interceptor = interceptors.get(index);
從攔截器里頭取下一個(gè)攔截器,因?yàn)閕ndex=1,這個(gè)時(shí)候取出的是BridgeInterceptor攔截器(處理配置請求頭等信息),執(zhí)行Response response = interceptor.intercept(next);
看下BridgeInterceptor攔截器的intercept()方法
@Override
public Response intercept(Chain chain) throws IOException {
Request userRequest = chain.request();
Request.Builder requestBuilder = userRequest.newBuilder();
RequestBody body = userRequest.body();
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());
}
//TODO 執(zhí)行下一個(gè)攔截器
Response networkResponse = chain.proceed(requestBuilder.build());
HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
Response.Builder responseBuilder = networkResponse.newBuilder()
.request(userRequest);
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();
}
代碼挺多,但是邏輯也清晰,就是為我們的請求,按照http協(xié)議添加一些請求頭信息,為后面使用 socket 寫出數(shù)據(jù)做準(zhǔn)備
配置一些請求頭信息 ,例如:
1.Content-Type 請求中的媒體類型信息
2.Content-Length 請求體body的長度
3.Host 請求域名
4.Connection: "Keep-Alive" 是否保持長連接
5.Cookie 等等....
關(guān)于http的內(nèi)容,大伙可以上網(wǎng)去搜一下對應(yīng)的文章了解一下..
然后調(diào)用Response networkResponse = chain.proceed(requestBuilder.build());
跟上面一樣,還是會(huì)回到RealInterceptorChain.proceed()方法里面,再次創(chuàng)建一個(gè)新的RealInterceptorChain對象,并且把 index+1,然后繼續(xù)執(zhí)行一下個(gè)攔截的intercept(next)方法,這里不貼出相同的源碼了.然后會(huì)執(zhí)行到CacheInterceptor攔截器
看一下CacheInterceptor.intercept(next)
@Override public Response intercept(Chain chain) throws IOException {
//TODO request對應(yīng)緩存的Response
Response cacheCandidate = cache != null
? cache.get(chain.request())
: null;
//TODO 執(zhí)行響應(yīng)緩存策略
long now = System.currentTimeMillis();
CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
Request networkRequest = strategy.networkRequest;
Response cacheResponse = strategy.cacheResponse;
if (cache != null) {
cache.trackResponse(strategy);
}
//TODO 緩存無效 關(guān)閉資源
if (cacheCandidate != null && cacheResponse == null) {
closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
}
// If we're forbidden from using the network and the cache is insufficient, fail.
//TODO 如果禁止使用網(wǎng)絡(luò),并且沒有緩存,就返回失敗
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();
}
// If we don't need the network, we're done.
//TODO 不使用網(wǎng)絡(luò)請求直接返回響應(yīng)
if (networkRequest == null) {
return cacheResponse.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.build();
}
//TODO 執(zhí)行下一個(gè)攔截器
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());
}
}
// If we have a cache response too, then we're doing a conditional get.
//TODO 如果存在緩存 更新
if (cacheResponse != null) {
//TODO 304響應(yīng)碼 自從上次請求后慢宗,請求需要響應(yīng)的內(nèi)容未發(fā)生改變
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());
}
}
//TODO 緩存Response
Response response = networkResponse.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
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;
}
這個(gè)攔截器是處理緩存相關(guān),具體細(xì)節(jié)這里不管,只分析主流程...
不過從注釋可以清晰的看出一些大概的邏輯
1.從緩存里面取出響應(yīng)結(jié)果Response cacheCandidate
2.判斷緩存是否失效,如果失效就關(guān)閉資源
3.判斷如果禁止使用網(wǎng)絡(luò),并且沒有緩存,就返回失敗
等等....
然后又繼續(xù)調(diào)用networkResponse = chain.proceed(networkRequest);
執(zhí)行下一個(gè)攔截器ConnectInterceptor
ConnectInterceptor.intercept(Chain chain)
@Override public Response intercept(Chain chain) throws IOException {
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Request request = realChain.request();
StreamAllocation streamAllocation = realChain.streamAllocation();
// We need the network to satisfy this request. Possibly for validating a conditional GET.
boolean doExtensiveHealthChecks = !request.method().equals("GET");
//TODO 連接服務(wù)器/復(fù)用socket
HttpCodec httpCodec = streamAllocation.newStream(client, chain, doExtensiveHealthChecks);
RealConnection connection = streamAllocation.connection();
//TODO 找到復(fù)用的 socket或者創(chuàng)建新的 socket,并且連接服務(wù)器,但是這里還沒有把請求寫出去
//TODO 然后執(zhí)行下一個(gè)攔截器
return realChain.proceed(request, streamAllocation, httpCodec, connection);
}
這個(gè)攔截器負(fù)責(zé)連接服務(wù)器,會(huì)調(diào)用streamAllocation.newStream
public HttpCodec newStream(
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 {
RealConnection resultConnection = findHealthyConnection(connectTimeout, readTimeout,
writeTimeout, pingIntervalMillis, connectionRetryEnabled,
doExtensiveHealthChecks);
//TODO HttpCodec 處理解析請求與響應(yīng)的工具類
HttpCodec resultCodec = resultConnection.newCodec(client, chain, this);
synchronized (connectionPool) {
codec = resultCodec;
return resultCodec;
}
} catch (IOException e) {
throw new RouteException(e);
}
}
newStream()方法里面會(huì)調(diào)用findHealthyConnection()去尋找一個(gè)健康的可用的連接來進(jìn)行socket連接
有關(guān)sockter連接部分還請大伙去查看對應(yīng)的資料,這里只需要知道:
1.TPC/IP協(xié)議是傳輸層協(xié)議,主要規(guī)范數(shù)據(jù)如何在網(wǎng)絡(luò)中傳輸
2.Socket則是對TCP/IP協(xié)議的封裝和應(yīng)用(程序員層面上)
3.Http 是應(yīng)用層協(xié)議,解決如何包裝數(shù)據(jù),然后通過Socket發(fā)送到服務(wù)器
4.這里的RealConnection類是對Socket的封裝,里面持有Socket的引用
5.這里的HttpCodec是處理解析請求與響應(yīng)的工具類
回到上面,通過調(diào)用streamAllocation.newStream(...)
連接之后,拿到一個(gè)HttpCodec,然后繼續(xù)執(zhí)行下一個(gè)攔截器,也就是最后的攔截器CallServerInterceptor,通過socket和服務(wù)器進(jìn)行I/O流讀寫操作
CallServerInterceptor.intercept()
@Override public Response intercept(Chain chain) throws IOException {
RealInterceptorChain realChain = (RealInterceptorChain) chain;
HttpCodec httpCodec = realChain.httpStream();
StreamAllocation streamAllocation = realChain.streamAllocation();
RealConnection connection = (RealConnection) realChain.connection();
Request request = realChain.request();
...
//TODO 把請求通過 socket 以http的協(xié)議格式,通過I/O流的形式寫出去
httpCodec.writeRequestHeaders(request);
realChain.eventListener().requestHeadersEnd(realChain.call(), request);
...
//TODO 請求寫出完成
httpCodec.finishRequest();
if (responseBuilder == null) {
realChain.eventListener().responseHeadersStart(realChain.call());
responseBuilder = httpCodec.readResponseHeaders(false);
}
//TODO 處理響應(yīng)
Response response = responseBuilder
.request(request)
.handshake(streamAllocation.connection().handshake())
.sentRequestAtMillis(sentRequestMillis)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
...
return response;
}
刪除了很多代碼.具體實(shí)現(xiàn)先不去看,如果大伙想知道,可以去搜索對應(yīng)方面的具體細(xì)節(jié)文章...
這里了解到:
1.在CallServerInterceptor這個(gè)攔截器,實(shí)現(xiàn)Socket與服務(wù)器進(jìn)行TCP連接,然后進(jìn)行I/O數(shù)據(jù)流的通信.
2.發(fā)送請求, Socket是以http協(xié)議的格式,把請求拆分,請求行,請求頭,請求體等等,一行一行寫出去的
3.接受響應(yīng), Socket也是以http協(xié)議的格式,把響應(yīng)結(jié)果一行一行的讀出來,然后再解析
Socket通信例子:
例如 : 用瀏覽器模擬 GET 去請求獲取天氣的接口,然后拿到結(jié)果
怎樣用Socket來實(shí)現(xiàn)請求呢?
java的jdk為我們提供了具體的實(shí)現(xiàn)Socket,直接創(chuàng)建使用就行
static void doHttp() throws Exception {
//創(chuàng)建一個(gè)Socket ,傳入 域名和端口,http默認(rèn)是80
Socket socket = new Socket("restapi.amap.com", 80);
//接受數(shù)據(jù)的輸入流
final BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//發(fā)送數(shù)據(jù) 輸出流
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
new Thread() {
@Override
public void run() {
while (true) {
String line = null;
try {
while ((line = br.readLine()) != null) {
System.out.println("recv :" + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start();
bw.write("GET /v3/weather/weatherInfo?city=%E9%95%BF%E6%B2%99&key=13cb58f5884f9749287abbead9c658f2 HTTP/1.1\r\n");
bw.write("Host: restapi.amap.com\r\n\r\n");
bw.flush();
}
1.創(chuàng)建一個(gè)Socket ,傳入域名和端口,http默認(rèn)是80
2.通過Socket 拿到接受數(shù)據(jù)的輸入流和發(fā)送數(shù)據(jù)的輸出流
3.按http協(xié)議規(guī)范,把請求寫出去bw.write("GET /v3/weathe....
和bw.write("Host: restapi.amap.com\r\n\r\n");
4.接受服務(wù)器響應(yīng)結(jié)果
打印結(jié)果:
recv :HTTP/1.1 200 OK
recv :Server: Tengine
recv :Date: Thu, 05 Jul 2018 09:47:14 GMT
recv :Content-Type: application/json;charset=UTF-8
recv :Content-Length: 253
recv :Connection: close
recv :X-Powered-By: ring/1.0.0
recv :gsid: 011178122113153078403472700229732459707
recv :sc: 0.010
recv :Access-Control-Allow-Origin: *
recv :Access-Control-Allow-Methods: *
recv :Access-Control-Allow-Headers: DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,
If-Modified-Since,Cache-Control,Content-Type,key,x-biz,x-info,platinfo,encr,enginever,gzipped,poiid
recv :
recv :{"status":"1","count":"1","info":"OK","infocode":"10000","lives":
[{"province":"廣東","city":"深圳市","adcode":"440300","weather":
"云","temperature":"29","winddirection":"南","windpower":"5","humidity":"77",
"reporttime":"2018-07-05 17:00:00"}]}
響應(yīng)也是一行一行讀寫出來
最后一個(gè)攔截器拿到服務(wù)器響應(yīng)結(jié)果,然后再依次往上面的攔截器返回response,這個(gè)流程就不多說了,到此一次通信就完成...
小結(jié):
okhttp采用責(zé)任鏈模式,每一個(gè)攔截器負(fù)責(zé)具體的每一塊的功能,降低每個(gè)功能模塊的耦合度,讓整體框架更加靈活,我們可以輕松的加入自己自定義的攔截器.
okhttp維護(hù)著一個(gè)連接池,能做到相同Host的socket復(fù)用