OkHttp3源碼學(xué)習(xí)之InterceptorChain

介紹

攔截器鏈贸典,采用責(zé)任鏈模式拓劝,將一次事物的耦合度降低雏逾。

源碼分析

RealInterceptorChain

RealInterceptorChain就是個(gè)List<Interceptor>,源碼比較簡(jiǎn)單,主要功能proceed

public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
      RealConnection 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;
}

RetryAndFollowUpInterceptor

RetryAndFollowUpInterceptor

RetryAndFollowUpInterceptor的責(zé)任是失敗重試和重定向郑临,主要功能在于intercept

 @Override public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    //創(chuàng)建一個(gè)新的流
    streamAllocation = new StreamAllocation(
        client.connectionPool(), createAddress(request.url()), callStackTrace);
    int followUpCount = 0;
    //重定向可能產(chǎn)生多個(gè)Response
    Response priorResponse = null;
    //循環(huán)直到取消或者拋出exception
    while (true) {
      ...
      //輔助判斷是否要釋放連接
      boolean releaseConnection = true;
      try {
        //取得下級(jí)返回的response
        response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
        releaseConnection = false;
      } catch (){
        //各種異常捕捉處理
        ...
      } finally {
        // We're throwing an unchecked exception. Release any resources.
        if (releaseConnection) {
          streamAllocation.streamFailed(null);
          streamAllocation.release();
        }
      }
      ...
      //重定向栖博,根據(jù)返回response生成新的request
      Request followUp = followUpRequest(response);
      ...
      //判斷是否是sameConnection(host==host&&port==port&&scheme==scheme)可復(fù)用鏈路 
      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;
    }
  }

BridgeInterceptor

BridgeInterceptor可以理解成轉(zhuǎn)換器

Bridges from application code to network code. First it builds a network request from a user request. Then it proceeds to call the network. Finally it builds a user response from the network response.

源碼非常簡(jiǎn)單,主要內(nèi)容在于intercept

  @Override public Response intercept(Chain chain) throws IOException {
    Request userRequest = chain.request();
    //組織Request Header包括這是keep-alive, Cookie添加厢洞,gzip等
    ....
    //傳遞
    Response networkResponse = chain.proceed(requestBuilder.build());
    //組織Response Header 包括cookie保存更新仇让,Gzip解壓等
    ....
    return responseBuilder.build();
  }

CacheInterceptor

緩存攔截器更具客戶(hù)端是否支持緩存和相關(guān)的緩存策略決定從網(wǎng)絡(luò)獲取或者從緩存獲取Response,主要內(nèi)容在于intercept

public Response intercept(Chain chain) throws IOException {
    Response cacheCandidate = cache != null
        ? cache.get(chain.request())
        : null;

    long now = System.currentTimeMillis();
    //根據(jù)緩存策略獲取緩存Request和Response
    CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
    Request networkRequest = strategy.networkRequest;
    Response cacheResponse = strategy.cacheResponse;
    ...
    //緩存不可用或者緩存過(guò)期躺翻,網(wǎng)絡(luò)獲取
    Response networkResponse = null;
    try {
      networkResponse = chain.proceed(networkRequest);
    } finally {
      // If we're crashing on I/O or otherwise, don't leak the cache body.
      if (networkResponse == null && cacheCandidate != null) {
        closeQuietly(cacheCandidate.body());
      }
    }
    ...
    //更新緩存
    return response;
  }

ConnectInterceptor

ConnectInterceptor建立與服務(wù)器的連接

  @Override public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Request request = realChain.request();
    //獲取可復(fù)用流
    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 = streamAllocation.newStream(client, doExtensiveHealthChecks);
    //根據(jù)HTTP/1.x(keep-alive)和HTTP/2(流復(fù)用)的復(fù)用機(jī)制丧叽,發(fā)起連接
    RealConnection connection = streamAllocation.connection();

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

CallServerInterceptor

CallServerInterceptor和服務(wù)器交互數(shù)據(jù)

 @Override public Response intercept(Chain chain) throws IOException {
     ...
    long sentRequestMillis = System.currentTimeMillis();
    //發(fā)送header數(shù)據(jù)
    httpCodec.writeRequestHeaders(request);

    Response.Builder responseBuilder = null;
    //根據(jù)是否支持100-continue,發(fā)送body數(shù)據(jù)
    if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
    ...
    }

    httpCodec.finishRequest();

    if (responseBuilder == null) {
      responseBuilder = httpCodec.readResponseHeaders(false);
    }

    Response response = responseBuilder
        .request(request)
        .handshake(streamAllocation.connection().handshake())
        .sentRequestAtMillis(sentRequestMillis)
        .receivedResponseAtMillis(System.currentTimeMillis())
        .build();

    int code = response.code();
    //response處理
    ...
    return response;
  }

擴(kuò)展

責(zé)任鏈中大體流程分析完公你,其中有很多可以深究的地方踊淳,包括緩存和多路復(fù)用的實(shí)現(xiàn)

緩存

Okhttp緩存涉及到internal cache(接口設(shè)計(jì)),cache(實(shí)現(xiàn)類(lèi))陕靠,CacheStrategy(緩存策略)迂尝,DiskLruCache(lru cache實(shí)現(xiàn)),具體可以參考BlackSwift寫(xiě)的
OkHttp3源碼分析[緩存策略] ,OkHttp3源碼分析[DiskLruCache]

多路復(fù)用

多路復(fù)用設(shè)計(jì)到包括StreamAllocation(上層流)剪芥,ConnectionPool(連接池)垄开, http1Codec,http2Codec税肪。
首先要了解HTTP/1(keep-alive)和HTTP/2(二進(jìn)制流)的相關(guān)知識(shí)溉躲,才能更好的理解OKhttp多路復(fù)用的實(shí)現(xiàn),具體可以參考
OkHttp 3.7源碼分析(五)——連接池
OkHttp3源碼分析[復(fù)用連接池]

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末益兄,一起剝皮案震驚了整個(gè)濱河市签财,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌偏塞,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,383評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件邦鲫,死亡現(xiàn)場(chǎng)離奇詭異灸叼,居然都是意外死亡神汹,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,522評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門(mén)古今,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)屁魏,“玉大人,你說(shuō)我怎么就攤上這事捉腥∶テ矗” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 157,852評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵抵碟,是天一觀的道長(zhǎng)桃漾。 經(jīng)常有香客問(wèn)我,道長(zhǎng)拟逮,這世上最難降的妖魔是什么撬统? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,621評(píng)論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮敦迄,結(jié)果婚禮上恋追,老公的妹妹穿的比我還像新娘。我一直安慰自己罚屋,他們只是感情好苦囱,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,741評(píng)論 6 386
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著脾猛,像睡著了一般撕彤。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上尖滚,一...
    開(kāi)封第一講書(shū)人閱讀 49,929評(píng)論 1 290
  • 那天喉刘,我揣著相機(jī)與錄音,去河邊找鬼漆弄。 笑死睦裳,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的撼唾。 我是一名探鬼主播廉邑,決...
    沈念sama閱讀 39,076評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼倒谷!你這毒婦竟也來(lái)了蛛蒙?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 37,803評(píng)論 0 268
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤渤愁,失蹤者是張志新(化名)和其女友劉穎牵祟,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體抖格,經(jīng)...
    沈念sama閱讀 44,265評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡诺苹,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,582評(píng)論 2 327
  • 正文 我和宋清朗相戀三年咕晋,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片收奔。...
    茶點(diǎn)故事閱讀 38,716評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡掌呜,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出坪哄,到底是詐尸還是另有隱情质蕉,我是刑警寧澤,帶...
    沈念sama閱讀 34,395評(píng)論 4 333
  • 正文 年R本政府宣布翩肌,位于F島的核電站模暗,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏摧阅。R本人自食惡果不足惜汰蓉,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,039評(píng)論 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望棒卷。 院中可真熱鬧顾孽,春花似錦、人聲如沸比规。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,798評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)蜒什。三九已至测秸,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間灾常,已是汗流浹背霎冯。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,027評(píng)論 1 266
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留钞瀑,地道東北人沈撞。 一個(gè)月前我還...
    沈念sama閱讀 46,488評(píng)論 2 361
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像雕什,于是被迫代替她去往敵國(guó)和親缠俺。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,612評(píng)論 2 350

推薦閱讀更多精彩內(nèi)容

  • okhttp3.6.0源碼分析系列文章整體內(nèi)容如下: okhttp3.6.0源碼分析準(zhǔn)備2——java知識(shí)okht...
    hello_小丁同學(xué)閱讀 564評(píng)論 0 1
  • 前言 做React Native的時(shí)候遇到業(yè)務(wù)線反饋的一個(gè)Bug:在使用Charles做代理的時(shí)候贷岸,將reactT...
    靈丞閱讀 12,735評(píng)論 2 36
  • 關(guān)于okhttp是一款優(yōu)秀的網(wǎng)絡(luò)請(qǐng)求框架壹士,關(guān)于它的源碼分析文章有很多,這里分享我在學(xué)習(xí)過(guò)程中讀到的感覺(jué)比較好的文章...
    蕉下孤客閱讀 3,599評(píng)論 2 38
  • 一 “高達(dá)”這兩個(gè)字偿警,寫(xiě)出來(lái)容易躏救,但是其背后所包含的,卻不是一兩篇文章螟蒸、一兩本書(shū)所能涵蓋得了盒使。從1979年到現(xiàn)在的...
    丁若柯閱讀 4,708評(píng)論 14 21
  • 星期二的下午睁本,爸爸請(qǐng)假帶我去死海玩,那里有五項(xiàng)游玩項(xiàng)目:溫泉水療忠怖、鹽水漂浮、礦鹽理療抄瑟、黑泥養(yǎng)生凡泣、鹽霧清肺,這五項(xiàng)我...
    毛蟲(chóng)苑楊浩軒閱讀 274評(píng)論 0 1