OkHttpClient的工作
- 建造者模式创建实例本身
- 通信的客户端,用来统一管理发起请求与解析响应。
- 实例化Dispatcher
请求任务调度器
,将会单独开篇讲述 - 实例化 ConnectionPool
连接池
,用来管理和复用连接,将会单独开篇讲述
源码分析
1. 内部类Builder源码分析
new OkHttpClient.Builder()
public Builder() {
dispatcher = new Dispatcher();
protocols = DEFAULT_PROTOCOLS;
connectionSpecs = DEFAULT_CONNECTION_SPECS;
eventListenerFactory = EventListener.factory(EventListener.NONE);
proxySelector = ProxySelector.getDefault();
if (proxySelector == null) {
proxySelector = new NullProxySelector();
}
cookieJar = CookieJar.NO_COOKIES;
socketFactory = SocketFactory.getDefault();
hostnameVerifier = OkHostnameVerifier.INSTANCE;
certificatePinner = CertificatePinner.DEFAULT;
proxyAuthenticator = Authenticator.NONE;
authenticator = Authenticator.NONE;
connectionPool = new ConnectionPool();
dns = Dns.SYSTEM;
followSslRedirects = true;
followRedirects = true;
retryOnConnectionFailure = true;
callTimeout = 0;
connectTimeout = 10_000;
readTimeout = 10_000;
writeTimeout = 10_000;
pingInterval = 0;
}
这里在初始化的时候做了一些数据初始化操作,需要特别注意的是初始化的时候就实例化了任务调度器
Dispatcher
和连接池ConnectionPool
。
常用的方法介绍
Builder().connectTimeout()
: 连接超时时长设置
public Builder connectTimeout(long timeout, TimeUnit unit) {
connectTimeout = checkDuration("timeout", timeout, unit);
return this;
}
Builder().readTimeout()
: 读取超时时长设置
public Builder readTimeout(long timeout, TimeUnit unit) {
readTimeout = checkDuration("timeout", timeout, unit);
return this;
}
Builder().writeTimeout()
: 写入超时时长设置
public Builder writeTimeout(long timeout, TimeUnit unit) {
writeTimeout = checkDuration("timeout", timeout, unit);
return this;
}
Builder().cache()
: 缓存设置
public Builder cache(@Nullable Cache cache) {
this.cache = cache;
this.internalCache = null;
return this;
}
Builder().build()
: 生成OkHttpClient对象方法
public OkHttpClient build() {
return new OkHttpClient(this);
}
2. OkHttpClient方法
newCall(Request)
: 生成RealCall对象实例
public Call newCall(Request request) {
return RealCall.newRealCall(this, request, false /* for web socket */);
}