OKHTTP简单使用总结

概述


OkHttp是一个高效的HTTP客户端,它具有特性:

允许所有同一个主机地址的请求共享同一个socket连接
使用连接池减少请求延时
透明的GZIP压缩减少响应数据的大小
缓存响应内容,避免一些完全重复的请求

请求主要处理类及UML见下图:


先了解下使用姿势,发送同步网络请求:
1
2
3
4
5
6
7
8
9
10
11
12
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(Constants.TEST_URL).build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
System.out.println(response.body().string());
} else {
System.out.println("网络异常");
}
} catch (IOException e) {
e.printStackTrace();
}

发送异步网络请求:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(Constants.TEST_URL).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println("网络异常");
}

@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
System.out.println(response.body().string());
} else {
System.out.println("网络异常");
}

}
});

OkHttpClient 构建


OkHttpClient 实例构建使用建造者模式,方便定制自己的网络请求工具
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public OkHttpClient() {
this(new Builder());
}

private 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.proxySelector = builder.proxySelector;
this.cookieJar = builder.cookieJar;
this.cache = builder.cache;
this.internalCache = builder.internalCache;
this.socketFactory = builder.socketFactory;

......

}

Dispatcher网络请求执行策略


主要成员变量:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 最大支持同时请求数
private int maxRequests = 64;
// 单个域名最大请求数
private int maxRequestsPerHost = 5;

// 请求线程池
private ExecutorService executorService;

// 等待执行的异步请求
private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>();

// 正在执行的异步请求
private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();

// 正在执行的同步请求
private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>();

例:更改同时支持最大请求数和单个域名同时最大请求数:

1
2
3
4
5
6
Dispatcher dispatcher = new Dispatcher();
dispatcher.setMaxRequests(20);
dispatcher.setMaxRequestsPerHost(3);
httpClient = new OkHttpClient.Builder()
.dispatcher(dispatcher)
.build();

Protocol 默认支持的请求协议


Protocol.HTTP_2
Protocol.SPDY_3 
Protocol.HTTP_1_1

ConnectionPool Socket链接池


1
2
3
4
5
6
7
8
// 最大缓存socket链接个数,默认5
private final int maxIdleConnections;
// 空闲回收时间,默认 5分钟
private final long keepAliveDurationNs;
// 缓存socket链接
private final Deque<RealConnection> connections = new ArrayDeque<>();
// 用于网络请求异常时自动切换请求ip
final RouteDatabase routeDatabase = new RouteDatabase();





文章目录
  1. 1. 概述
  2. 2. OkHttpClient 构建
    1. 2.1. Dispatcher网络请求执行策略
    2. 2.2. Protocol 默认支持的请求协议
    3. 2.3. ConnectionPool Socket链接池