andorid jar/库源码解析之okhttp3

目录:andorid jar/库源码解析 

Okhttp3:

  作用:

    用于网络编程(http,https)的快速开发。

  栗子:

// 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对象,同时赋值默认值

  ②:返回一个 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.cnblogs.com/Supperlitt/p/12772798.html