Okhttp3 攔截器鏈過(guò)程淺析(四)

攔截器:Okhttp中提供的一種強(qiáng)大的機(jī)制崖堤,可以實(shí)現(xiàn)網(wǎng)絡(luò)監(jiān)聽(tīng)吗氏、請(qǐng)求/響應(yīng)重寫(xiě)幅垮、請(qǐng)求失敗重試等功能的實(shí)現(xiàn)(攔截器不區(qū)分異步/同步)

Okhttp不管是異步/同步乌昔,在RealCall.java中都會(huì)執(zhí)行Response result = getResponseWithInterceptorChain();

  • 同步
RealCall.java

@Override public Response execute() throws IOException {
    synchronized (this) {
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    captureCallStackTrace();
    eventListener.callStart(this);
    try {
      client.dispatcher().executed(this);
      Response result = getResponseWithInterceptorChain();//執(zhí)行該方法
      .....省略無(wú)用代碼
  }

  • 異步
RealCall.java

@Override public void enqueue(Callback responseCallback) {
    ...省略無(wú)用代碼
    client.dispatcher().enqueue(new AsyncCall(responseCallback));//跟到AsyncCall中
  }

==============================分割線(xiàn)=========================

AsyncCall.execute();

@Override protected void execute() {
      boolean signalledCallback = false;
      try {
        Response response = getResponseWithInterceptorChain();//異步也是執(zhí)行該方法
        ....省略無(wú)用代碼
    }

接下來(lái)看一下getResponseWithInterceptorChain()具體做了什么操作隙疚,源碼如下:

//方法字面意思:得到一個(gè)具有攔截器鏈的響應(yīng)
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));//網(wǎng)絡(luò)連接攔截器
    if (!forWebSocket) {
      interceptors.addAll(client.networkInterceptors());
    }
    interceptors.add(new CallServerInterceptor(forWebSocket));

    //攔截器鏈
    Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
        originalRequest, this, eventListener, client.connectTimeoutMillis(),
        client.readTimeoutMillis(), client.writeTimeoutMillis());

    //執(zhí)行RealInterceptorChain.proceed();方法,下面將具體分析
    return chain.proceed(originalRequest);
  }

上面的getResponseWithInterceptorChain()是通過(guò)RealInterceptorChain.proceed();方法得到一個(gè)攔截器鏈磕道,下面具體看一下proceed()方法:

public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
      RealConnection connection) throws IOException {
    if (index >= interceptors.size()) throw new AssertionError();

    calls++;

    // If we already have a stream, confirm that the incoming request will use it.
    if (this.httpCodec != null && !this.connection.supportsUrl(request.url())) {
      throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
          + " must retain the same host and port");
    }

    // If we already have a stream, confirm that this is the only call to chain.proceed().
    if (this.httpCodec != null && calls > 1) {
      throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
          + " must call proceed() exactly once");
    }

    // Call the next interceptor in the chain.
    // 在這里供屉,得到了 next 下一個(gè)鏈,構(gòu)造函數(shù)中將 index+1 
    RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
        connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
        writeTimeout);
    //interceptors 就是從構(gòu)造函數(shù)中,得到的List<Interceptpr>
    //也就是在RealCall.getResponseWithInterceptorChain()贯卦;中添加的所有的攔截器
    Interceptor interceptor = interceptors.get(index);
    //在這里资柔,執(zhí)行攔截器的intercept();方法
    //在具體攔截器的intercept()方法中,又會(huì)調(diào)用next chain的proceed();方法
    //構(gòu)成了一個(gè)鏈
    Response response = interceptor.intercept(next);

    ....省略部分代碼

    return response;
  }

proceed()方法執(zhí)行過(guò)程大概是:
在內(nèi)部將index+1撵割,得到下一個(gè)RealInterceptorChain贿堰,通過(guò)具體的攔截器的intercept()方法,繼續(xù)執(zhí)行下一個(gè)鏈的proceed();方法啡彬,依次直到最后一個(gè)攔截器羹与,從而形成一個(gè)鏈(有點(diǎn)類(lèi)似于遞歸,依次往內(nèi)部請(qǐng)求,結(jié)果從最內(nèi)部一層一層傳到最外層)庶灿。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末纵搁,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子往踢,更是在濱河造成了極大的恐慌腾誉,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,284評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件峻呕,死亡現(xiàn)場(chǎng)離奇詭異利职,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)瘦癌,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)猪贪,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人讯私,你說(shuō)我怎么就攤上這事热押。” “怎么了斤寇?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,614評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵桶癣,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我抡驼,道長(zhǎng)鬼廓,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,671評(píng)論 1 293
  • 正文 為了忘掉前任致盟,我火速辦了婚禮碎税,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘馏锡。我一直安慰自己雷蹂,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,699評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布杯道。 她就那樣靜靜地躺著匪煌,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上萎庭,一...
    開(kāi)封第一講書(shū)人閱讀 51,562評(píng)論 1 305
  • 那天霜医,我揣著相機(jī)與錄音,去河邊找鬼驳规。 笑死肴敛,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的吗购。 我是一名探鬼主播医男,決...
    沈念sama閱讀 40,309評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼捻勉!你這毒婦竟也來(lái)了镀梭?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,223評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤踱启,失蹤者是張志新(化名)和其女友劉穎报账,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體禽捆,經(jīng)...
    沈念sama閱讀 45,668評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡笙什,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,859評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了胚想。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,981評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡芽隆,死狀恐怖浊服,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情胚吁,我是刑警寧澤牙躺,帶...
    沈念sama閱讀 35,705評(píng)論 5 347
  • 正文 年R本政府宣布,位于F島的核電站腕扶,受9級(jí)特大地震影響孽拷,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜半抱,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,310評(píng)論 3 330
  • 文/蒙蒙 一脓恕、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧窿侈,春花似錦炼幔、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,904評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春跺讯,著一層夾襖步出監(jiān)牢的瞬間枢贿,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,023評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工刀脏, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留萨咕,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,146評(píng)論 3 370
  • 正文 我出身青樓火本,卻偏偏與公主長(zhǎng)得像危队,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子钙畔,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,933評(píng)論 2 355