Okhttp攔截器原理
OkHttp幾乎所有的和請求相關的動作都在幾個攔截器中處理的,本質上來說其實就是一個遞歸的方式調用所有的攔截器
原理大概想這個圖一樣

RealInterceptorChain
這個類是一個所有的攔截器的管理類,他負責調度所有的攔截器,主要的實現方法在
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException
比較重要的就這幾行
RealInterceptorChain next = new RealInterceptorChain(
interceptors, streamAllocation, httpCodec, connection, index + 1, request);
// interceptors.get(index); 這個index是當前的攔截器的位置 ,上面的index+1是下一個攔截器
Interceptor interceptor = interceptors.get(index);
Response response = interceptor.intercept(next);
所有的攔截器繼承Interceptor接口重寫了intercept(Chain chain)這個方法,這個方法的chain就是這段代碼構建的。
構建這個Chain必須需要 interceptors , index ,其他的可以根據業務需求確定。
- interceptors是所有的攔截器,
- index 是下一個攔截器的位置
然后拿到當前index的Interceptor調用intercept()方法并將構建的chain傳進去就可以了
在一個攔截器中的intercept()方法要求有兩點:
1.必須調用chain.proceed()將時間傳下去
2.chain.proceed()不能調用兩次,否側代碼會重新再走一次,OkHttp對這個做了一個拋出異常處理
我學到的東西
攔截器的這種編程思想很不錯,非常適合一個任務需要很多手續處理一樣。
示例代碼