目錄:andorid jar/庫原始碼決議
Okhttp3:
作用:
用于網路編程(http,https)的快速開發,
栗子:
// okHttpClient定義成全域靜態,或者單例,不然重復new可能導致連接數耗盡 OkHttpClient okHttpClient = new OkHttpClient(); String url = "https://www.test.com"; byte[] data = https://www.cnblogs.com/Supperlitt/p/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物件,同時賦值默認值
②:回傳一個 RequestBody物件,該物件包含,型別,長度,和寫入資料的方法,
③:創建一個Request$Builder物件,默認使用GET請求,對addHeader進行添加到List<String>集合中,name,value.trim(),一個header用兩條,
④:賦值請求地址,同時特殊處理ws->http,wss->https,對url進行拆分決議,.得到url中的schema,host,port,name,password,path等
⑤:賦值RequestBody和method成POST
⑥:用所有的Request$Builder成員,初始化一個Request物件,
⑦:用OkHttpClient物件的默認值,初始化一個OkHttpClient$Builder物件
⑧:回傳一個OkHttpClient物件,值來自OkHttpClient$Builder
⑨:通過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'
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/7434.html
標籤:Android
