1
2
3
4
5
transient URLStreamHandler handler;

public URLConnection openConnection() throws java.io.IOException {
return handler.openConnection(this);
}

HttpUrlConnection 的对象是由 URL 对象调用 handler.openConnection 来常见完成的,这里的 handler 的类型为 URLStreamHandler,这个 handler 又是由 factory.createURLStreamHandler(protocol) 根据协议来创建的,最终它的实现为 com.android.okhttp.HttpHandler 或者 com.android.okhttp.HttpsHandler。

https://cs.android.com/android/platform/superproject/+/master:external/okhttp/repackaged/android/src/main/java/com/android/okhttp/HttpHandler.java;l=41?q=com.android.okhttp.HttpHandler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
protected URLConnection openConnection(URL url) throws IOException {
return newOkUrlFactory(null /* proxy */).open(url);
}

protected OkUrlFactory newOkUrlFactory(Proxy proxy) {
OkUrlFactory okUrlFactory = createHttpOkUrlFactory(proxy);
okUrlFactory.client().setConnectionPool(configAwareConnectionPool.get());
return okUrlFactory;
}

public static OkUrlFactory createHttpOkUrlFactory(Proxy proxy) {
OkHttpClient client = new OkHttpClient();
// 0 代表不限制
client.setConnectTimeout(0, TimeUnit.MILLISECONDS);
client.setReadTimeout(0, TimeUnit.MILLISECONDS);
client.setWriteTimeout(0, TimeUnit.MILLISECONDS);
// 重定向设置
client.setFollowRedirects(HttpURLConnection.getFollowRedirects());
// 默认 https 下不自动跟踪重定向
client.setFollowSslRedirects(false);
client.setConnectionSpecs(CLEARTEXT_ONLY);
if (proxy != null) {
client.setProxy(proxy);
}
OkUrlFactory okUrlFactory = new OkUrlFactory(client);
OkUrlFactories.setUrlFilter(okUrlFactory, CLEARTEXT_FILTER);
ResponseCache responseCache = ResponseCache.getDefault();
if (responseCache != null) {
AndroidInternal.setResponseCache(okUrlFactory, responseCache);
}
return okUrlFactory;
}

这样就完成了 OkHttpClient 对象的创建了。它返回的 URLConnection 对象的实现为 HttpURLConnectionImpl 或者为 HttpsURLConnectionImpl,可见 这里,之后 HttpUrlConnection 发生的操作都是由它完成的。