当前位置: 移动技术网 > IT编程>移动开发>Android > andorid jar/库源码解析之okhttp3

andorid jar/库源码解析之okhttp3

2020年04月25日  | 移动技术网IT编程  | 我要评论

熊黛林真实身高,猪易网,六安热线

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

  源码:

  引入:

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

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网