https://square.github.io/okhttp/
https://github.com/square/okhttp/
0 概述
okhttp是一个现代的网络请求框架
Http/2 支持 所有访问同一个主机的Request都共用一个socket
connection pool 连接池 减少请求延迟
GZIP 压缩数据,减少传输所用的带宽
Response Cache 避免重复性的Request
1 使用
Get
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
Post
public static final MediaType JSON
= MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(json, JSON);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
Async
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override public void onResponse(Call call, Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(responseBody.string());
}
}
});
}
2 源码
2.0 请求过程
2.1 OkHttpClient
dispatcher
interceptors
networkInterceptors
connectionPool
proxy
newCall()
2.2 Call
Response execute()
enqueue(Callback responseCallback)
2.3 Request
url
method
headers
body
tag
cacheControl
2.4 Response
request
protocol
code
message
headers
body
handshake
2.5 RealInterceptorChain
interceptors
transmitter
index
request
call
exchange
2.6 Interceptor
- Response intercept(Chain chain)
2.7 Cache
- DiskLruCache cache;
2.8 Connection
Route route();
Socket socket();
Handshake handshake();
Protocol protocol();
connectSocket
source
sink
connectionPool
3 架构
-
中间层
OKhttp 通过很多中间拦截器来对 Request Response 进行加工
实现了数据的 流式链式处理
生产者
-
分发器
- 调度器 通过不同状态的 任务队列 来调度任务
- readyCalls runningCalls
消费者
缓存
- 拦截器
- 类似责任链的效果,链式处理,链式返回