OKHttp原始碼解析(5)----攔截器ConnectInterceptor

王大帝發表於2018-12-06

系列文章

OKio原始碼解析

OKHttp原始碼解析(1)----整體流程

OKHttp原始碼解析(2)----攔截器RetryAndFollowUpInterceptor

OKHttp原始碼解析(3)----攔截器BridgeInterceptor

OKHttp原始碼解析(4)----攔截器CacheInterceptor

OKHttp原始碼解析(5)----攔截器ConnectInterceptor

OKHttp原始碼解析(6)----攔截器CallServerInterceptor

1.簡介

Opens a connection to the target server and proceeds to the next interceptor.

連線攔截器,負責和伺服器建立連線

2.原始碼解析

  @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");
     //在連線池中找個可用的連結,並建立HttpCodec
    HttpCodec httpCodec = streamAllocation.newStream(client, doExtensiveHealthChecks);
    RealConnection connection = streamAllocation.connection();

    return realChain.proceed(request, streamAllocation, httpCodec, connection);
  }

複製程式碼

連線攔截器的程式碼比較簡單,主要是將網路設定組合起來,給下一個攔截器----CallServerInterceptor,用於向伺服器發起真正的網路請求。這些網路設施主要有request(請求)、streamAllocation(網路設施,可以獲取HttpCodec和RealConnection)、HttpCodec(htt編解碼器)和RealConnection(連線)

實際的網路請求可以在攔截器CallServerInterceptor檢視。

小結

未完待續。

相關文章