筆記--OkHttp攔截器

今天捋清楚了OkHttp的攔截器機(jī)制哈恰,并且理解之后試著模仿著寫了一套攔截器的架構(gòu)。把筆記記下來志群,方便以后查看着绷。

OkHttp攔截器

用OkHttp做網(wǎng)絡(luò)請求的時(shí)候,可以很方便的根據(jù)自身需要構(gòu)造很多攔截器锌云,以實(shí)現(xiàn)不同的功能荠医,對請求體和返回信息進(jìn)行處理。甚至可能這個(gè)機(jī)制太好用了宾抓,連OkHttp本身最后對服務(wù)器的請求也是通過定義一個(gè)攔截器來實(shí)現(xiàn)的子漩,這個(gè)攔截器叫CallServerInterceptor,是攔截器鏈條里面的最后一個(gè)攔截器石洗。
我們來看一個(gè)基本的網(wǎng)絡(luò)請求幢泼,它的流程很簡單:請求,等待響應(yīng)讲衫,拿到響應(yīng)信息缕棵,結(jié)束。
大致如下圖:


基本網(wǎng)絡(luò)請求流程

但是很多時(shí)候我們有需求在這個(gè)流程中做很多自己需要的操作涉兽,比如打印日志啦招驴,添加統(tǒng)一的請求消息頭啦,根據(jù)返回信息的共同特征做特定的統(tǒng)一操作啦(比如token過期跳登錄頁面)枷畏,還有序列化對象啦等等等等很多各式各樣的需求别厘。這個(gè)時(shí)候攔截器就派上用場了,它的功能極其強(qiáng)大拥诡,基本可以滿足你在從請求到返回響應(yīng)過程中想做的一切騷操作触趴。
我們看看加入攔截器之后流程的變化:


添加一個(gè)攔截器

我們捋一捋攔截器做的這幾件事

[1] 首先氮发,攔截器接收一個(gè)request,拿到這個(gè)request之后冗懦,可以決定要不要做加工處理爽冕,然后把加工好的request交給下一個(gè)攔截器,這是第一件事披蕉。
[2] 自己處理完了之后颈畸,要驅(qū)動(dòng)下一個(gè)攔截器執(zhí)行它的操作,不能一層一層處理到自己這里就停下來了没讲,導(dǎo)致鏈條運(yùn)行中斷眯娱,這一步必須做。這是第二件事食零。
[3] 處理完request困乒,還要看看下一層返回來的response自己要不要處理一下寂屏,加工好了之后再把它丟給上一層贰谣。這是第三件事。
[4] 第四件事其實(shí)包含在1和3里面迁霎,就是根據(jù)上一層傳下來的request和下一層返回的response信息決定要不要做額外的操作吱抚,這個(gè)其實(shí)是附帶的操作,和整體攔截器的運(yùn)行流程相關(guān)性不大考廉。

根據(jù)上面幾條秘豹,依次來看,我們來看看實(shí)現(xiàn)一個(gè)攔截器要實(shí)現(xiàn)的基本方法:

class InterceptorA implements Interceptor{
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            //處理requeset...
            Response response = chain.proceed(request);
            //處理response...
            return response;
        }
    }

實(shí)現(xiàn)攔截器需要實(shí)現(xiàn)一個(gè)方法昌粤,就是intercept方法既绕,但是傳入的參數(shù)卻不是Request,而是一個(gè)Chain對象涮坐,這個(gè)對象凄贩,是一個(gè)靈魂中樞。
通過上面的描述袱讹,我們可以知道疲扎,攔截器機(jī)制其實(shí)是通過責(zé)任鏈模式來實(shí)現(xiàn)的,所以這個(gè)靈魂中樞對象起名為Chain(鏈條)捷雕。
Chain里面保存了傳入的Request對象椒丧,可以隨時(shí)取出來進(jìn)行加工處理。
Chain里面保存了整個(gè)的攔截器列表救巷,可以取出下一個(gè)攔截器壶熏,執(zhí)行intercept方法,也因此浦译,Chain可以從下一個(gè)攔截器的intercept方法中獲取下一層返回回來的Response棒假,然后對Response進(jìn)行加工處理俄占,再返回給上一層。
這就是上面的攔截器要做的三件事淆衷,都依賴Chain這個(gè)對象缸榄。
然后我們來看看Chain的實(shí)現(xiàn),看看它都做了那些事...
我們知道祝拯,責(zé)任鏈模式中每一個(gè)鏈塊執(zhí)行完自己的操作之后都要繼續(xù)驅(qū)動(dòng)下一個(gè)鏈塊繼續(xù)執(zhí)行操作甚带,這就要求每一個(gè)鏈塊需要保存有下一個(gè)鏈塊的執(zhí)行方法入口,有的人通過一個(gè)公共的管理方法來驅(qū)動(dòng)執(zhí)行佳头,也有的直接保存下一個(gè)鏈塊的對象鹰贵,攔截器這里的處理方式是,讓每一個(gè)鏈塊都持有了整個(gè)攔截器列表的實(shí)體康嘉,執(zhí)行完這一個(gè)之后碉输,從列表中取出下一個(gè),繼續(xù)執(zhí)行亭珍。

/**
 * A concrete interceptor chain that carries the entire interceptor chain: all application
 * interceptors, the OkHttp core, all network interceptors, and finally the network caller.
 */
public final class RealInterceptorChain implements Interceptor.Chain {
  private final List<Interceptor> interceptors;//重點(diǎn)
  private final StreamAllocation streamAllocation;
  private final HttpCodec httpCodec;
  private final RealConnection connection;
  private final int index;//重點(diǎn)
  private final Request request;
  private final Call call;
  private final EventListener eventListener;
  private final int connectTimeout;
  private final int readTimeout;
  private final int writeTimeout;
  private int calls;
  ...
  ...
}

上面的 List<Interceptor> interceptors是整個(gè)所有的攔截器列表敷钾,index是當(dāng)前的執(zhí)行位置,根據(jù)index肄梨,可以從list中取出下一個(gè)有效的攔截器阻荒,繼續(xù)執(zhí)行。
它的構(gòu)造方法里有11個(gè)參數(shù):

public RealInterceptorChain(List<Interceptor> interceptors, StreamAllocation streamAllocation,
      HttpCodec httpCodec, RealConnection connection, int index, Request request, Call call,
      EventListener eventListener, int connectTimeout, int readTimeout, int writeTimeout) {
    this.interceptors = interceptors;
    this.connection = connection;
    this.streamAllocation = streamAllocation;
    this.httpCodec = httpCodec;
    this.index = index;
    this.request = request;
    this.call = call;
    this.eventListener = eventListener;
    this.connectTimeout = connectTimeout;
    this.readTimeout = readTimeout;
    this.writeTimeout = writeTimeout;
  }

其中和攔截器運(yùn)行機(jī)制相關(guān)的關(guān)鍵參數(shù)有三個(gè):

List<Interceptor> interceptors;//完整的攔截器列表
int index;//當(dāng)前的執(zhí)行位置
Request request;//上一層傳入的Request

這就是它驅(qū)動(dòng)下一層攔截器繼續(xù)執(zhí)行所依賴的基本信息众羡。
那么具體怎么取出下一個(gè)攔截器繼續(xù)執(zhí)行下一層的呢侨赡?
我們都知道,在實(shí)現(xiàn)Interceptor接口的時(shí)候粱侣,去實(shí)現(xiàn)它的intercept(Chain chain)方法羊壹,有一行代碼是必須要執(zhí)行的,那就是chain.proceed(request)齐婴,哪怕你啥也不做油猫,你也得寫成下面這個(gè)樣子:

class InterceptorB implements Interceptor{
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            return chain.proceed(request);
        }
    }

為啥必須執(zhí)行這行代碼呢,因?yàn)榫褪撬?fù)責(zé)去驅(qū)動(dòng)下一層攔截器執(zhí)行操作尔店,不寫這行代碼眨攘,攔截器鏈條走到這一層,就斷了嚣州,整個(gè)鏈條的處理就會停在這里鲫售。
我們來看一下proceed方法的具體實(shí)現(xiàn):

@Override 
public Response proceed(Request request) throws IOException {
    return proceed(request, streamAllocation, httpCodec, connection);
 }
 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.
    RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
        connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
        writeTimeout);
    Interceptor interceptor = interceptors.get(index);
    Response response = interceptor.intercept(next);

    // Confirm that the next interceptor made its required call to chain.proceed().
    if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) {
      throw new IllegalStateException("network interceptor " + interceptor
          + " must call proceed() exactly once");
    }

    // Confirm that the intercepted response isn't null.
    if (response == null) {
      throw new NullPointerException("interceptor " + interceptor + " returned null");
    }

    if (response.body() == null) {
      throw new IllegalStateException(
          "interceptor " + interceptor + " returned a response with no body");
    }

    return response;
  }

取出里面關(guān)鍵的代碼出來看:

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, call, eventListener, connectTimeout, readTimeout,
        writeTimeout);
    Interceptor interceptor = interceptors.get(index);
    Response response = interceptor.intercept(next);
    ...
    ...
}

上面的注釋也寫的很清晰了:調(diào)用鏈條中的下一個(gè)攔截器。第一行代碼该肴,構(gòu)造下一個(gè)攔截器的Chain,傳入本層的request情竹,index+1,以及攔截器列表匀哄。然后從攔截器列表中取出下一個(gè)攔截器秦效,傳入構(gòu)造好的Chain對象雏蛮,執(zhí)行intercept(chain)方法。下一層的方法處理完阱州,返回response挑秉,本層通過proceed()方法取得response,再決定要不要繼續(xù)做處理苔货,再繼續(xù)返回給上一層犀概。
到這一步,基本就把攔截器的工作流程梳理清楚了夜惭,再回頭來看實(shí)現(xiàn)攔截器的方法里做的事情姻灶,就清晰很多了:

class InterceptorA implements Interceptor{
        @Override
        public Response intercept(Chain chain) throws IOException {
            //上一層構(gòu)造好的chain對象,傳入本層诈茧,里面包含了整個(gè)的攔截器列表和上一層傳入的request對象
            Request request = chain.request();//chain里面可以隨時(shí)取出request對象進(jìn)行加工處理
            //處理requeset...

            //porceed方法負(fù)責(zé)將本層加工處理好的request對象構(gòu)造出下一層的chain對象
            //并驅(qū)動(dòng)執(zhí)行下一層攔截器的intercept(Chain chain) 方法产喉,獲取下一層返回的response
            Response response = chain.proceed(request);
            
            //獲取到下一層返回回來的response之后,根據(jù)自身需要來決定是否要處理response或者根據(jù)
            //response的信息決定要不要做一些額外的事情
            //處理response...

            return response;//返回response給上一層
        }
    }

這就是單個(gè)攔截器所做的所有事情敢会。
然后曾沈,當(dāng)加入多個(gè)攔截器之后,處理的大致流程就變得如下圖所示:


多層攔截器

以上走触,攔截器整個(gè)的運(yùn)行機(jī)制基本就梳理完了晦譬。

...@Y(^ _ ^)Y@ ...

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市互广,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌卧土,老刑警劉巖惫皱,帶你破解...
    沈念sama閱讀 219,188評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異尤莺,居然都是意外死亡旅敷,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評論 3 395
  • 文/潘曉璐 我一進(jìn)店門颤霎,熙熙樓的掌柜王于貴愁眉苦臉地迎上來媳谁,“玉大人,你說我怎么就攤上這事友酱∏缫簦” “怎么了?”我有些...
    開封第一講書人閱讀 165,562評論 0 356
  • 文/不壞的土叔 我叫張陵缔杉,是天一觀的道長锤躁。 經(jīng)常有香客問我,道長或详,這世上最難降的妖魔是什么系羞? 我笑而不...
    開封第一講書人閱讀 58,893評論 1 295
  • 正文 為了忘掉前任郭计,我火速辦了婚禮,結(jié)果婚禮上椒振,老公的妹妹穿的比我還像新娘昭伸。我一直安慰自己,他們只是感情好澎迎,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,917評論 6 392
  • 文/花漫 我一把揭開白布勋乾。 她就那樣靜靜地躺著,像睡著了一般嗡善。 火紅的嫁衣襯著肌膚如雪辑莫。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,708評論 1 305
  • 那天罩引,我揣著相機(jī)與錄音各吨,去河邊找鬼。 笑死袁铐,一個(gè)胖子當(dāng)著我的面吹牛揭蜒,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播剔桨,決...
    沈念sama閱讀 40,430評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼屉更,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了洒缀?” 一聲冷哼從身側(cè)響起瑰谜,我...
    開封第一講書人閱讀 39,342評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎树绩,沒想到半個(gè)月后萨脑,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,801評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡饺饭,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,976評論 3 337
  • 正文 我和宋清朗相戀三年渤早,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片瘫俊。...
    茶點(diǎn)故事閱讀 40,115評論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡鹊杖,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出扛芽,到底是詐尸還是另有隱情骂蓖,我是刑警寧澤,帶...
    沈念sama閱讀 35,804評論 5 346
  • 正文 年R本政府宣布胸哥,位于F島的核電站涯竟,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜庐船,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,458評論 3 331
  • 文/蒙蒙 一银酬、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧筐钟,春花似錦揩瞪、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,008評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至壹将,卻和暖如春嗤攻,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背诽俯。 一陣腳步聲響...
    開封第一講書人閱讀 33,135評論 1 272
  • 我被黑心中介騙來泰國打工妇菱, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人暴区。 一個(gè)月前我還...
    沈念sama閱讀 48,365評論 3 373
  • 正文 我出身青樓闯团,卻偏偏與公主長得像,于是被迫代替她去往敵國和親仙粱。 傳聞我的和親對象是個(gè)殘疾皇子房交,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,055評論 2 355