天天看點

OKHTTP源碼解析筆記(一)

OkHttpClient簡稱為OHC

1、OHC配置一些預設設定

//第一步擷取okHttpClient對象
OkHttpClient client = new OkHttpClient.Builder()
        .cache(new Cache(getCacheDir(),10240*1024))
        .connectTimeout(20, TimeUnit.SECONDS)
        .followRedirects(true)
        .build();
           

builder類看一下

OKHTTP源碼解析筆記(一)

builer中

1、dispatcher建立了任務排程器(建立了線程池,管理所有任務,它能拿到目前請求隊列有哪些)

2、Protocol 請求網絡的預設版本設定為1.1,2.0

3、Dns.SYSTEM    DNS解析

4、逾時處理

。。。等等一系列的設定

二、構造Request

使用建造者設計模式

//第二步建構Request對象
Request request = new Request.Builder()
        .url("http://www.baidu.com")
        .get()
        .build();
           

看一下這個Builder,它屬于Request中的靜态内部類,它傳回的是Builder本身,可以實作連點操作

OKHTTP源碼解析筆記(一)

3、

//第三步建構Call對象
Call call = client.newCall(request);
           
OKHTTP源碼解析筆記(一)

 RealCall.newRealCall方法

OKHTTP源碼解析筆記(一)

 實際上就是RealCall 執行了enqueue方法

OKHTTP源碼解析筆記(一)

先執行一個同步方法來判斷異常,client拿到了dispatcher(任務管理器),dispatcher來執行了

enqueue方法,又把我們傳入進來的匿名内部類的回調接口傳到AsyncCall中。

AsyncCall實際上是Runnable

OKHTTP源碼解析筆記(一)

看一下dispatcher中的enqueue方法

OKHTTP源碼解析筆記(一)

readyAsyncCalls是一個準備請求隊列,把建立的Call加入到這個裡,下一步執行

promoteAndExecute方法

OKHTTP源碼解析筆記(一)

 會周遊我們已經加入的Runnable,最後執行了asyncall.executeon這個方法

executorService是一個線程池,任務調試器把建立好的線程池傳入進了AsynCall裡去執行

executeOn方法,線程池又執行了目前的runnable。

(這段代碼是OHT的核心)

OKHTTP源碼解析筆記(一)

AsyncCall繼承了一個NamedRunnable 

OKHTTP源碼解析筆記(一)
OKHTTP源碼解析筆記(一)
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, this, eventListener, client.connectTimeoutMillis(),
      client.readTimeoutMillis(), client.writeTimeoutMillis());

  return chain.proceed(originalRequest);
}
           

 OHC的主要源碼就過眼一遍啦!

整個流程就是 new HttpClient -----  建立線程池 ----建立了CallBack 并把它封裝進入Runnable中---然後執行execute

(線程池去執行runnable方法)-----runnable方法中已經設定了攔截器

仿寫OkHttp架構

繼續閱讀