幾個關(guān)鍵類以及接口
-
RealInterceptorChain
-
Interceptor
RealInterceptorChain
RealInterceptorChain
實現(xiàn)了Interceptor
接口,調(diào)用源頭來自于RealCall
的getResponseWithInterceptorChain
方法
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
List<Interceptor> interceptors = new ArrayList<>();
/**
* 1
*/
interceptors.addAll(client.interceptors());
interceptors.add(retryAndFollowUpInterceptor);
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));
/**
* 2
*/
Interceptor.Chain chain = new RealInterceptorChain(
interceptors, null, null, null, 0, originalRequest);
return chain.proceed(originalRequest);
}
1. 第一處是把自定義的攔截器先加入進去谷炸,然后把okhttp內(nèi)置的一些攔截器按照功能順序add進list里
2. 第二處是整個攔截器工作的源頭羞福,先new了一個RealInterceptorChain
,index為0,把初始的request
傳了進去,然后調(diào)用proceed
獲取請求的response
接下來看一下proceed方法的具體實現(xiàn),忽略掉一些檢查
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException {
if (index >= interceptors.size()) throw new AssertionError();
calls++;
/**
* 1
*/
// Call the next interceptor in the chain.
RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
writeTimeout);
Interceptor interceptor = interceptors.get(index);
Response response = interceptor.intercept(next);
return response;
}
先是檢查一下index是否超出interceptors
也就是攔截器list的長度肉拓,接著又new了一個RealInterceptorChain
鸭丛,把當(dāng)前RealInterceptorChain
的一些參數(shù)屬性都傳了進去竞穷,并且在這里把index + 1
,這個地方很重要,在這里可以把RealInterceptorChain
想象成把攔截器給包裝了起來鳞溉,然后用下一個攔截器生成一個新的RealInterceptorChain
中瘾带,然后把index+1
下標(biāo)的chain
傳進了當(dāng)前攔截器的intercept
方法里,也就是我們自定義攔截器的時候需要重寫的intercept
方法熟菲,也就是說我們添加的攔截器里的intercept
方法中RealInterceptorChain
對象看政,實際上里面包含有整個request
以及下一個攔截器朴恳。所以就形成了一條鏈,每一個攔截器都持有下一個攔截器經(jīng)過包裝之后的RealInterceptorChain
對象,直到攔截器鏈的最后一個攔截器CallServerInterceptor
這個攔截器會做最后的處理允蚣,然后開始請求生成Response
并且返回于颖。攔截器可以通過intercept
方法獲取下一個攔截器return
的response
,而且會通過proceed
方法向下一個攔截器傳遞自己處理過的Requeset
到這里總結(jié)一下各個方法以及類的作用
-
RealInterceptorChain
包裝了攔截器以及網(wǎng)絡(luò)請求的信息
-
RealInterceptorChain.proceed
參數(shù)中有
Request
,是上一個攔截器包裝過后的Request
,然后將下一個攔截器和整個Request
的信息包裝成RealInterceptorChain
,并且會調(diào)用當(dāng)前攔截器的intercept
方法把下一個攔截器(RealInterceptorChain
)傳進去嚷兔,并且獲取到Response
-
Interceptor.intercept
方法參數(shù)是下一個
Chain
也就是RealInterceptorChain
森渐,然后調(diào)用RealInterceptorChain.request()
去獲取請求,調(diào)用RealInterceptorChain.proceed()
去獲取Response