/*
* Copyright (C) 2012 Square, Inc.
*照猫画虎 依葫芦画瓢 个人能力理解解释,老外属性和方法不写功能注释,这样很不爽
这里面是不是用到了一个设计模式叫构建者?
(建议大家学习设计模式可以先学习概念然后再到实际开源项目中去寻找具体的例子,然后再结合设计模式的概
念来翻来覆去的比较,就像烙大饼一样,翻来翻去,否则光烙一面大饼就烙糊了O(∩_∩)O哈哈~)
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3;
import java.net.MalformedURLException;
import java.net.Proxy;//代理
import java.net.ProxySelector;//代理选择器
import java.net.Socket;//socket
import java.net.UnknownHostException;//位置的主机异常
import java.security.GeneralSecurityException;//生成安全异常?
import java.security.KeyStore;//秘钥存储?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;//随机数
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;//时间单位
import javax.annotation.Nullable;
import javax.net.SocketFactory;//socket工厂
import javax.net.ssl.HostnameVerifier;//主机名校验?
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.internal.Internal;
import okhttp3.internal.Util;
import okhttp3.internal.cache.InternalCache;//内部高速缓存
import okhttp3.internal.connection.RealConnection;//重新连接?
import okhttp3.internal.connection.RouteDatabase;//路由数据库
import okhttp3.internal.connection.StreamAllocation;
import okhttp3.internal.platform.Platform;//平台
import okhttp3.internal.tls.CertificateChainCleaner;
import okhttp3.internal.tls.OkHostnameVerifier;
import okhttp3.internal.ws.RealWebSocket;
/**
* Factory for {@linkplain Call calls}, which can be used to send HTTP requests and read their
* responses.
*
* <h3>OkHttpClients should be shared</h3>
*
* <p>OkHttp performs best when you create a single {@code OkHttpClient} instance and reuse it for
* all of your HTTP calls. This is because each client holds its own connection pool and thread
* pools. Reusing connections and threads reduces latency and saves memory. Conversely, creating a
* client for each request wastes resources on idle pools.
*
* <p>Use {@code new OkHttpClient()} to create a shared instance with the default settings:
* <pre> {@code
*
* // The singleton HTTP client.
* public final OkHttpClient client = new OkHttpClient();
* }</pre>
*
* <p>Or use {@code new OkHttpClient.Builder()} to create a shared instance with custom settings:
* <pre> {@code
*
* // The singleton HTTP client.
* public final OkHttpClient client = new OkHttpClient.Builder()
* .addInterceptor(new HttpLoggingInterceptor())
* .cache(new Cache(cacheDir, cacheSize))
* .build();
* }</pre>
*
* <h3>Customize your client with newBuilder()</h3>
*
* <p>You can customize a shared OkHttpClient instance with {@link #newBuilder()}. This builds a
* client that shares the same connection pool, thread pools, and configuration. Use the builder
* methods to configure the derived client for a specific purpose.
*
* <p>This example shows a call with a short 500 millisecond timeout: <pre> {@code
*
* OkHttpClient eagerClient = client.newBuilder()
* .readTimeout(500, TimeUnit.MILLISECONDS)
* .build();
* Response response = eagerClient.newCall(request).execute();
* }</pre>
*
* <h3>Shutdown isn't necessary</h3>
*
* <p>The threads and connections that are held will be released automatically if they remain idle.
* But if you are writing a application that needs to aggressively release unused resources you may
* do so.
*
* <p>Shutdown the dispatcher's executor service with {@link ExecutorService#shutdown shutdown()}.
* This will also cause future calls to the client to be rejected. <pre> {@code
*
* client.dispatcher().executorService().shutdown();
* }</pre>
*
* <p>Clear the connection pool with {@link ConnectionPool#evictAll() evictAll()}. Note that the
* connection pool's daemon thread may not exit immediately. <pre> {@code
*
* client.connectionPool().evictAll();
* }</pre>
*
* <p>If your client has a cache, call {@link Cache#close close()}. Note that it is an error to
* create calls against a cache that is closed, and doing so will cause the call to crash.
* <pre> {@code
*
* client.cache().close();
* }</pre>
*
* <p>OkHttp also uses daemon threads for HTTP/2 connections. These will exit automatically if they
* remain idle.
*/
public class OkHttpClient implements Cloneable, Call.Factory, WebSocket.Factory {
static final List<Protocol> DEFAULT_PROTOCOLS = Util.immutableList(
Protocol.HTTP_2, Protocol.HTTP_1_1);
static final List<ConnectionSpec> DEFAULT_CONNECTION_SPECS = Util.immutableList(
ConnectionSpec.MODERN_TLS, ConnectionSpec.CLEARTEXT);
//静态代码块
static {
Internal.instance = new Internal() {
@Override public void addLenient(Headers.Builder builder, String line) {
builder.addLenient(line);
}
@Override public void addLenient(Headers.Builder builder, String name, String value) {
builder.addLenient(name, value);
}
@Override public void setCache(Builder builder, InternalCache internalCache) {
builder.setInternalCache(internalCache);
}
@Override public boolean connectionBecameIdle(
ConnectionPool pool, RealConnection connection) {
return pool.connectionBecameIdle(connection);
}
@Override public RealConnection get(ConnectionPool pool, Address address,
StreamAllocation streamAllocation, Route route) {
return pool.get(address, streamAllocation, route);
}
@Override public boolean equalsNonHost(Address a, Address b) {
return a.equalsNonHost(b);
}
@Override public Socket deduplicate(
ConnectionPool pool, Address address, StreamAllocation streamAllocation) {
return pool.deduplicate(address, streamAllocation);
}
@Override public void put(ConnectionPool pool, RealConnection connection) {
pool.put(connection);
}
@Override public RouteDatabase routeDatabase(ConnectionPool connectionPool) {
return connectionPool.routeDatabase;
}
@Override public int code(Response.Builder responseBuilder) {
return responseBuilder.code;
}
@Override
public void apply(ConnectionSpec tlsConfiguration, SSLSocket sslSocket, boolean isFallback) {
tlsConfiguration.apply(sslSocket, isFallback);
}
@Override public HttpUrl getHttpUrlChecked(String url)
throws MalformedURLException, UnknownHostException {
return HttpUrl.getChecked(url);
}
@Override public S
okhttp3 3.8.1版本 中类OkHttpClient.java的源码剖析学习
本文深入剖析了okhttp3 3.8.1版本中OkHttpClient类的源码,详细解释了其内部工作原理,包括请求发送、响应处理和连接管理等方面,帮助读者理解OkHttp的网络请求实现机制。
摘要由CSDN通过智能技术生成