简介
OkHttp是一个高效的HTTP客户端,它有以下默认特性:
·支持HTTP/2,允许所有同一个主机地址的请求共享同一个socket连接
·连接池减少请求延时
·透明的GZIP压缩减少响应数据的大小
·缓存响应内容,避免一些重复的请求
OkHttp官网:https://square.github.io/okhttp/
Github地址 :https://github.com/square/okhttp
使用
implementation 'com.squareup.okhttp3:okhttp:3.9.0'
4.*版本使用的是Kotlin
同步请求
//创建okhttpclient对象
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
//创建Request 对象
Request request = new Request.Builder().get()
.url("https://api.github.com/")
.build();
//创建call对象
Call call= okHttpClient .newCall(request );
Response mResponse = call.execute();
异步请求
//创建okhttpclient对象
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
//创建Request 对象
Request request = new Request.Builder()
.url("https://api.github.com/")
.build();
//创建call对象
Call call = okHttpClient.newCall(request);
//通过call.enqueue方法来提交异步请求
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 异步请求失败的操作
}
@Override
public void onResponse(Call call, Response response) {
// 异步请求成功的操作
}
});
onResponse() 和onFailure()回调方法在子线程执行的
OkHttp的使用比较简单,按照上面的一套流程下来就可以执行一次请求
重点在于分析源码,所以对于OkHttp的使用并不做过多的介绍
OkHttpClient创建
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
这一个过程到底做了什么
最后调用 OkHttpClient(Builder builder)得到实例并赋值
OkHttpClient(Builder builder) {
this.dispatcher = builder.dispatcher;
this.proxy = builder.proxy;
this.protocols = builder.protocols;
this.connectionSpecs = builder.connectionSpecs;
this.interceptors = Util.immutableList(builder.interceptors);
this.networkInterceptors = Util.immutableList(builder.networkInterceptors);
this.eventListenerFactory = builder.eventListenerFactory;
this.proxySelector = builder.proxySelector;
this.cookieJar = builder.cookieJar;
this.cache = builder.cache;
this.internalCache = builder.internalCache;
this.socketFactory = builder.socketFactory;
boolean