android开发分享andorid jar/库源码解析之okhttp3

目录:andorid jar/库源码解析 Okhttp3: 作用: 用于网络编程(http,https)的快速开发。 栗子: // okHttpClient定义成全局静态,或者单例,不然重复new可能导致连接数耗尽 OkHttpClient okHttpClient = new OkHttpClie …

目录: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();

  源码解读:

  andorid jar/库源码解析之okhttp3

  ①:创建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 读取数据,并且返回(因为是流读取,所以只能调用一次)

  源码:

  引入:

implementation 'com.squareup.okhttp3:okhttp:3.12.1'

 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/addevelopment/898902.html

(0)
上一篇 2021年10月23日
下一篇 2021年10月23日

精彩推荐