andorid jar/庫源碼解析之okhttp3

目錄:andorid jar/庫源碼解析 html

Okhttp3:

  做用:

    用於網絡編程(http,https)的快速開發。git

  栗子:

// okHttpClient定義成全局靜態,或者單例,否則重複new可能致使鏈接數耗盡
OkHttpClient okHttpClient = new OkHttpClient();
String url = "https://www.test.com";
byte[] data = new byte[] { 1 };

okhttp3.RequestBody body = okhttp3.RequestBody.create(MediaType.parse("application/octet-stream"), data);

// Request
Request request = new Request.Builder().addHeader("Authorization", "Bearer XXXXXXXX").url(url).post(body).build();

// Response
Response response = okHttpClient.newBuilder().build().newCall(request).execute();

// 注意:這裏是string不是toString
final String msg = response.body().string();

  源碼解讀:

  

  ①:建立OkHttpClient對象,同時賦值默認值github

  ②:返回一個 RequestBody對象,該對象包含,類型,長度,和寫入數據的方法。編程

  ③:建立一個Request$Builder對象,默認使用GET請求,對addHeader進行添加到List<String>集合中,name,value.trim(),一個header用兩條。網絡

  ④:賦值請求地址,同時特殊處理ws->http,wss->https。對url進行拆分解析,.獲得url中的schema,host,port,name,password,path等app

  ⑤:賦值RequestBody和method成POSTpost

  ⑥:用全部的Request$Builder成員,初始化一個Request對象。ui

  ⑦:用OkHttpClient對象的默認值,初始化一個OkHttpClient$Builder對象url

  ⑧:返回一個OkHttpClient對象,值來自OkHttpClient$Builderspa

  ⑨:經過OkHttpClient和Request構造一個,RealCall對象。

  ⑩:調用RealCall的execute方法。a>把RealCall對象添加到,運行Call的集合中。b>建立 RealInterceptorChain 對象進行通信。 c> 調用 proceed 方法。。d> 建立 List<Interceptor> 集合。循環調用 Interceptor的intercept方法,進行處理請求。的細節。

    順序: RetryAndFollowUpInterceptor、BridgeInterceptor、CacheInterceptor、ConnectInterceptor、networkInterceptors、CallServerInterceptor

    最後在CallServerInterceptor 中的intercept中。執行建立一個 RealBufferedSink 對象,用於寫入數據(post內容),而後調用finishRequest。

    讀取readResponseHeaders ,獲得 Response.Builder 對象,使用這個對象,構造一個Response對象,把request,超時等信息,賦值到response上,判斷response.code==100,從新readResponseHeaders,更新code的值。

    調用responseHeadersEnd,完成讀取同步,而後讀取body:openResponseBody,獲得 ResponseBody對象。賦值給Response對象,返回

  ⑪:獲得ResponseBody對象而已,沒啥說的

  ⑫:使用Okio 讀取數據,而且返回(由於是流讀取,因此只能調用一次)

  源碼:https://github.com/square/okhttp

  引入:

implementation 'com.squareup.okhttp3:okhttp:3.12.1'
相關文章
相關標籤/搜索