系列文章
OkHttp学习(一) OSI七层模型和TCP四层模型
OkHttp学习(二) 3.10.0版本的简单使用及其流程梳理
OkHttp学习(三) 3.10.0版本源码阅读之线程池
OkHttp学习(四) 3.10.0版本源码阅读之构建者设计模式
OkHttp学习(五) 3.10.0版本源码阅读之责任链设计模式
OkHttp学习(六) 3.10.0版本源码中的拦截器
OkHttp学习(七) 手写OkHttp之框架搭建
OkHttp学习(八) 手写OkHttp之网络请求实现
OkHttp学习(九) OkHttp的连接池手写实现
版本信息
OkHttp 3.10.0
简单使用
添加依赖
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
}
网络请求
private void okHttp() throws Exception {
// 创建OkHttpClient,构建者模式
OkHttpClient httpClient = new OkHttpClient.Builder().build();
// 创建Request,构建者模式
Request request = new Request.Builder()
.get()
.url("https://www.baidu.com").build();
// 创建一个Call
Call realCall = httpClient.newCall(request);
// 同步方法
// Response response = realCall.execute();
// String string = response.body().string();
// Log.d(TAG, string);
// 异步请求接口
realCall.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 请求失败
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// 请求成功
// 打印响应的内容
String string = response.body().string();
Log.d(TAG, string);
}
});
// 不可再次执行realCall.enqueue方法,内部会抛出异常IllegalStateException
/**
* synchronized (this) {
* if (executed) throw new IllegalStateException("Already Executed");
* executed = true;
* }
*/
}
流程梳理
用OkHttpClient和Request的参数组装出一个Call对象, 然后使用Call的异步方法发送请求,首先会判断当前请求数是否超过maxRequests,每个主机正在请求的接口数量是否超过maxRequestsPerHost,如果超过了, 则只是将请求放到队列中等待处理。如果没有超过,则直接加入正在执行的队列,并且执行AsyncCall的execute方法。AsyncCall的execute方法,从责任链中取的Response,具体如何取的下篇文章分析。 接着将Response通过回调接口返回给调用方,这样一次完整的请求就结束了。
总结
OkHttp使用底层的Socket,并没有使用Google提供的网络请求框架。 OkHttp是一个高效的HTTP库:
- 支持http、 SPDY、http2.0、 websocket协议
- 通过连接池和SPDY、http2.0的共享socket提高网络性能
- 连接恢复。
- 实现了HttpURLConnection和Apache HTTP Client接口。
- 组件式。单独的功能独立出来。