OkHttp的请求分为同步请求和异步请求,下面我们先来分析同步请求的执行流程。
首先,看一下OkHttp执行同步请求的简单示例:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://baidu.com")
.build();
Response response;
try {
response = client.newCall(request).execute();
Log.d(TAG, response.body() != null ? response.body().toString() : null);
} catch (IOException e) {
e.printStackTrace();
}
第一步,我们new了一个OkHttpClient,使用了默认的构造函数。
public OkHttpClient() {
this(new Builder());
}
这里返回了一个new Builder(). 这个大家应该很熟悉,一个Builder模式的写法。跟进源码部分,可以看到它主要做了一些成员变量的初始化工作。比如Dispatcher,是请求分发器,连接池管理的connectionPool, 我们后面将重点分析, 以及一些timeout的设置等。
public Builder() {
dispatcher = new Dispatcher();
protocols = DEFAULT_PROTOCOLS;
connectionSpecs = DEFAULT_CONNECTION_SPECS;
eventListenerFactory = EventListener.factory(EventListener.NONE);
proxySelector = ProxySelector.getDefault();
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 = tr