Android-OKHttp底層原理淺析(二)

上一篇Android-OKHTTP底層原理淺析(一)講到

getResponseWithInterceptorChain()

這個(gè)方法過,今天接著這部分繼續(xù),開始之前我們先預(yù)習(xí)一下——責(zé)任鏈模式。

ok,這個(gè)責(zé)任鏈模式是什么意思呢,首先“鏈”,就如我們生活中常見的鎖鏈,一環(huán)扣一環(huán),首尾相應(yīng),你想長(zhǎng)點(diǎn),就多接幾圈,短點(diǎn)就少接幾圈,對(duì)的,很靈活是吧,所以責(zé)任鏈模式的一大特征是靈活性。在咱們的編程世界里,每一個(gè)環(huán)就等于一個(gè)節(jié)點(diǎn)、一個(gè)對(duì)象,有各自負(fù)責(zé)的邏輯。當(dāng)一個(gè)請(qǐng)求從鏈的首端發(fā)出,沿著鏈的路徑依次傳遞給每一個(gè)節(jié)點(diǎn),直到有節(jié)點(diǎn)處理這個(gè)請(qǐng)求為止,我們將這種模式稱之為責(zé)任鏈模式。這種模式在篩選攔截方面的需求用處較多(比如咱們今天的okhttp)。第二個(gè)特征叫解耦,怎么理解這個(gè)概念呢,舉個(gè)栗子:
比如你們部門要出去嗨了,準(zhǔn)備跟公司申請(qǐng)一筆經(jīng)費(fèi),OK,這個(gè)時(shí)候一般都會(huì)去找人事部對(duì)吧,人事部職員一看,幫你核算一下人數(shù),登記一下時(shí)間,ok,轉(zhuǎn)達(dá)給人事部大佬,大佬接到申請(qǐng)單,掃了一眼,大概沒問題了,但是批不了呀他,為啥,因?yàn)樨?cái)政大權(quán)不在他手上,他立馬轉(zhuǎn)交給了財(cái)務(wù)部,財(cái)務(wù)部妹妹接過手,嗯都填的差不多了,就是人數(shù)跟經(jīng)費(fèi)有點(diǎn)超,他這邊不好批,所以轉(zhuǎn)給了財(cái)務(wù)部大佬,財(cái)務(wù)部大佬大手一揮,同意,然后層層返回,最后人事跟你說,OK 去嗨吧 記得開發(fā)票。
仔細(xì)想想,如果不是上帝視角,你覺得你接觸的有多少角色? 沒錯(cuò),可能只有第一次的人事妹妹,最后告知你OK的也是她。后面的事你不須理會(huì),哪天后面的流程有變動(dòng)也不關(guān)你事(這就是靈活性),這就是責(zé)任鏈第二大特征。
在Android的源碼中,比較經(jīng)典的責(zé)任鏈場(chǎng)景就是事件分發(fā),有興趣的筒子可以去了解一下ViewGroup是如何將事件派發(fā)到子view的。
好,啰嗦完了,有了這個(gè)概念之后咱們繼續(xù)講okhttp。

Response getResponseWithInterceptorChain() throws IOException {
    // Build a full stack of interceptors.
    List<Interceptor> interceptors = new ArrayList<>();
    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));

    Interceptor.Chain chain = new RealInterceptorChain(
        interceptors, null, null, null, 0, originalRequest);
    return chain.proceed(originalRequest);
  }

首先這里定義了一個(gè)攔截器集合,里面分別有retryAndFollowUpInterceptor , BridgeInterceptor , CacheInterceptor ,ConnectInterceptor ,CallServerInterceptor, 以及我們?cè)谕饷孀远x的client.interceptors(),client.networkInterceptors(),一個(gè)一個(gè)來,先看第一個(gè)retryAndFollowUpInterceptor

@Override public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    streamAllocation = new StreamAllocation(
        client.connectionPool(), createAddress(request.url()), callStackTrace);

    int followUpCount = 0;
    Response priorResponse = null;
    while (true) {
      if (canceled) {
        streamAllocation.release();
        throw new IOException("Canceled");
      }

      Response response = null;
      boolean releaseConnection = true;
      try {
        response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
        releaseConnection = false;
      } catch (RouteException e) {
        // The attempt to connect via a route failed. The request will not have been sent.
        if (!recover(e.getLastConnectException(), false, request)) {
          throw e.getLastConnectException();
        }
        releaseConnection = false;
        continue;
      } catch (IOException e) {
        // An attempt to communicate with a server failed. The request may have been sent.
        boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
        if (!recover(e, requestSendStarted, request)) throw e;
        releaseConnection = false;
        continue;
      } finally {
        // We're throwing an unchecked exception. Release any resources.
        if (releaseConnection) {
          streamAllocation.streamFailed(null);
          streamAllocation.release();
        }
      }

      // Attach the prior response if it exists. Such responses never have a body.
      if (priorResponse != null) {
        response = response.newBuilder()
            .priorResponse(priorResponse.newBuilder()
                    .body(null)
                    .build())
            .build();
      }

      Request followUp = followUpRequest(response);

      if (followUp == null) {
        if (!forWebSocket) {
          streamAllocation.release();
        }
        return response;
      }

      closeQuietly(response.body());

      if (++followUpCount > MAX_FOLLOW_UPS) {
        streamAllocation.release();
        throw new ProtocolException("Too many follow-up requests: " + followUpCount);
      }

      if (followUp.body() instanceof UnrepeatableRequestBody) {
        streamAllocation.release();
        throw new HttpRetryException("Cannot retry streamed HTTP body", response.code());
      }

      if (!sameConnection(response, followUp.url())) {
        streamAllocation.release();
        streamAllocation = new StreamAllocation(
            client.connectionPool(), createAddress(followUp.url()), callStackTrace);
      } else if (streamAllocation.codec() != null) {
        throw new IllegalStateException("Closing the body of " + response
            + " didn't close its backing stream. Bad interceptor?");
      }

      request = followUp;
      priorResponse = response;
    }
  }

有點(diǎn)長(zhǎng),但是我們只看關(guān)鍵點(diǎn),首先這個(gè)攔截器是一個(gè)重定向攔截器,他的工作是負(fù)責(zé)創(chuàng)建一個(gè)連接對(duì)象,以及處理一些異??葱璨恍枰匦掳l(fā)起請(qǐng)求,首先創(chuàng)建了一個(gè)streamAllocation連接對(duì)象(注意只是創(chuàng)建,沒有連接,請(qǐng)多看他幾眼,后面的某一個(gè)攔截器你會(huì)又看到他的了),傳參分別為連接池,連接地址,堆棧對(duì)象。接下來創(chuàng)建了一個(gè)while循環(huán)while (true) {} 其中有一句

response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);

這里是執(zhí)行下一個(gè)攔截器的意思,從外面一層可以看出接下來的攔截器是BridgeInterceptor,怎樣看出是執(zhí)行下一個(gè)呢,我們點(diǎn)開proceed進(jìn)去,你會(huì)發(fā)現(xiàn)

public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
      Connection connection) throws IOException {
   <省略部分代碼>

    // Call the next interceptor in the chain.
    RealInterceptorChain next = new RealInterceptorChain(
        interceptors, streamAllocation, httpCodec, connection, index + 1, request);
    Interceptor interceptor = interceptors.get(index);
    Response response = interceptor.intercept(next);

  <省略部分代碼>

    return response;
  }

是吧,index + 1,所以接下來幾個(gè)攔截器也是通過這樣的方式去調(diào)用下一個(gè)的。
好,回到上面,當(dāng)執(zhí)行下個(gè)攔截器之后,后面的代碼就是等到里面的攔截器執(zhí)行完了,返回了之后才會(huì)繼續(xù)走的了。

Request followUp = followUpRequest(response);

      if (followUp == null) {
        if (!forWebSocket) {
          streamAllocation.release();
        }
        return response;
      }

這里是判斷是否重定向或者是超時(shí)重試,接下來還有一些判斷是否超過最大限制

if (++followUpCount > MAX_FOLLOW_UPS) {
      streamAllocation.release();
      throw new ProtocolException("Too many follow-up requests: " + followUpCount);
    }

以及是否有相同連接

if (!sameConnection(response, followUp.url())) {
      streamAllocation.release();
      streamAllocation = new StreamAllocation(
          client.connectionPool(), createAddress(followUp.url()), callStackTrace);
    } else if (streamAllocation.codec() != null) {
      throw new IllegalStateException("Closing the body of " + response
          + " didn't close its backing stream. Bad interceptor?");
    }

一系列判斷,這個(gè)攔截器的任務(wù)就到這過,簡(jiǎn)單來講的一個(gè)流程就是

(前)創(chuàng)建連接對(duì)象,
開啟循環(huán),
執(zhí)行下一個(gè)攔截器,
——(數(shù)據(jù)返回后)如果有異常,判斷是否需要恢復(fù),
檢查是否符合要求(符合則返回結(jié)果),
是否超過限制(超過拋出異常停止循環(huán)),
是否有相同的連接(如果有則復(fù)用,沒有則新建)。

ok,第一個(gè)攔截器的內(nèi)容過,看第二個(gè)BridgeInterceptor

@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());
    }

    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);
      responseBuilder.body(new RealResponseBody(strippedHeaders, Okio.buffer(responseBody)));
    }

    return responseBuilder.build();
  }

這是一個(gè)橋攔截器,放眼望去,是不是看到了很多熟悉的東西?(如果你不熟悉。。。當(dāng)我沒說[反手就是一巴掌.png])
是的,這里在負(fù)責(zé)請(qǐng)求的拼裝,全局的來講應(yīng)該稱之為轉(zhuǎn)換,因?yàn)楹竺娴臄r截器返回的數(shù)據(jù)也會(huì)經(jīng)過這里轉(zhuǎn)換之后才會(huì)回到我們剛剛講的第一個(gè)攔截器retryAndFollowUpInterceptor那里去的

Response networkResponse = chain.proceed(requestBuilder.build());

這句代碼之上就是一些請(qǐng)求包裝,具體的每個(gè)點(diǎn)就不細(xì)說了,比如cookie什么的,都可以自定義的,否則就添加默認(rèn)的,這句代碼就是執(zhí)行了下一個(gè)攔截器,執(zhí)行完成后數(shù)據(jù)返回,接下來

HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());

public static void receiveHeaders(CookieJar cookieJar, HttpUrl url, Headers headers) {
    if (cookieJar == CookieJar.NO_COOKIES) return;

    List<Cookie> cookies = Cookie.parseAll(url, headers);
    if (cookies.isEmpty()) return;

    cookieJar.saveFromResponse(url, cookies);
  }

這里解析服務(wù)器返回的Hearder(如果cookiejar為空則不做處理)

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)));
        }

這里判斷是否支持gzip壓縮,可以的話就使用Okio庫處理
ok,這個(gè)攔截器做的主要是

(前)對(duì)Hearder的一些處理,協(xié)議的包裝(默認(rèn)還是自定義)
執(zhí)行下一個(gè)攔截器
——(數(shù)據(jù)返回后)
判斷是否支持gzip,
數(shù)據(jù)處理完返回至上一層攔截器retryAndFollowUpInterceptor

接下來的幾個(gè)攔截器我們?cè)谙乱黄v,文章太長(zhǎng)看的臉疼~
Android-OKhttp底層原理淺析(三)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容