Okhttp攔截器原理

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對這個做了一個拋出異常處理

我學到的東西

攔截器的這種編程思想很不錯,非常適合一個任務需要很多手續處理一樣。
示例代碼

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容