随着Google抛弃HttpClient和Volley的逐步没落,OkHttp越来越受到开发者的青睐。
高楼大厦也是由一砖一瓦堆积而成,OKHttp这个牛逼的框架也是如此,也是由最基础的代码按照一定的结构设计开发而成。那么今天我们就透过现象来看本质,一点点的来分析OkHttp的原理。
文章基于最新的3.9.0版本进行分析,如果存在描述不正的地方,还请各位看官指正。
我们将分两个部分,分别讲解同步和异步请求。
1.同步请求
示例
/**
* 同步get请求。
*
* @param url 请求的URL
* @return 请求的返回结果
* @throws IOException 中间可能产生的异常
*/
public static String get(String url) throws IOException {
//1.实例化一个OkHttpClient实例
//好像也只能通过这个唯一的构造方法来创建对象了,我们可以考虑在应用中将其设计为单例使用
//也可以通过Builder模式创建
OkHttpClient client = new OkHttpClient();
//2.构造一个Request请求
//这几乎是最简单的请求构造方法
Request request = new Request.Builder()
.url(url)
.build();
//3.执行一个同步请求,得到返回结果
Response response = client.newCall(request).execute();
//4.处理返回结果
if(response.isSuccessful()){
return response.body().string();
}else{
throw new IOException("Unexpected code:"+response.code());
}
}
示例分析
OkHttpClient client = new OkHttpClient();
看似简单的一句代码,其实内部做了很多的操作。
1.OkHttpClient构造
//外部使用时唯一可访问的构造方法
public OkHttpClient() {
this(new Builder());
}
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.eventListenerFactory = builder.eventListenerFactory;
this.proxySelector = builder.proxySelector;
this.cookieJar = builder.cookieJar;
this.cache = builder.cache;
this.internalCache = builder.internalCache;
this.socketFactory = builder.socketFactory;
boolean isTLS = false;
for (ConnectionSpec spec : connectionSpecs) {
isTLS = isTLS || spec.isTls();
}
if (builder.sslSocketFactory != null || !isTLS) {
this.sslSocketFactory = builder.sslSocketFactory;
this.certificateChainCleaner = builder.certificateChainCleaner;
} else {
X509TrustManager trustManager = systemDefaultTrustManager();
this.sslSocketFactory = systemDefaultSslSocketFactory(trustManager);
this.certificateChainCleaner = CertificateChainCleaner.get(trustManager);
}
this.hostnameVerifier = builder.hostnameVerifier;
this.certificatePinner = builder.certificatePinner.withCertificateChainCleaner(
certificateChainCleaner);
this.proxyAuthenticator = builder.proxyAuthenticator;
this.authenticator = builder.authenticator;
this.connectionPool = builder.connectionPool;
this.dns = builder.dns;
this.followSslRedirects = builder.followSslRedirects;
this.followRedirects = builder.followRedirects;
this.retryOnConnectionFailure = builder.retryOnConnectionFailure;
this.connectTimeout = builder.connectTimeout;
this.readTimeout = builder.readTimeout;
this.writeTimeout = builder.writeTimeout;
this.pingInterval = builder.pingInterval;
if (interceptors.contains(null)) {
throw new IllegalStateException("Null interceptor: " + interceptors);
}
if (networkInterceptors.contains(null)) {
throw new IllegalStateException("Null network interceptor: " + networkInterceptors);
}
}
很明显OkHttpClient的构造使用了设计模式中的[Builder模式]。
关于Builder模式,在此不再描述,相信大家应该对此比较熟悉。
2.OkHttpClient.Builder构造
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 = true;
connectTimeout = 10_000;
readTimeout = 10_000;
writeTimeout = 10_000;
pingInterval = 0;
}
public OkHttpClient build() {
return new OkHttpClient(this);
}
Builder是OkHttpClient的静态内部类,主要是初始化一些OkHttpClient需要使用到的属性,上述代码是一些默认设置。
当然,你也可以根据自己的实际需求自定义设置这些参数值。
3.Request构造
Request的构造同样采用了[Builder模式],在此不再赘述。
//2.构造一个Request请求
//这几乎是最简单的请求构造方法
Request request = new Request.Builder()
.url(url)
.build();
//因为Request构造方法是包级私有的,所以不能直接new对象
//我们可以通过Builder来构造Request对象
Request(Builder builder) {
this.url = builder.url;
this.method = builder.method;
this.headers = builder.headers.build();
this.body = builder.body;
this.tag = builder.tag != null ? builder.tag : this;
}
//class Builder
public static class Builder {
HttpUrl url;
String method;
Headers.Builder headers;
RequestBody body;
Object tag;
public Builder() {
this.method = "GET";
this.headers = new Headers.Builder();
}
Builder(Request request) {
this.url = request.url;
this.method = request.method;
this.body = request.body;
this.tag = request.tag;
this.headers = request.headers.newBuilder();
}
public Request build() {
if (url == null) throw new IllegalStateException("url == null");
return new Request(this);
}
}
4.RealCall:真正的请求执行者
真正的流程开始执行是从生成RealCall开始的,RealCall也是真正的请求执行者。
//3.执行一个同步请求,得到返回结果
Response response = client.newCall(request).execute();
public Call newCall(Request request) {
return RealCall.newRealCall(this, request, false /* for web socket */);
}
private RealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
this.client = client;
this.originalRequest = originalRequest;
this.forWebSocket = forWebSocket;
//创建了失败重定向拦截器
this.retryAndFollowUpInterceptor = new RetryAndFollowUpInterceptor(client, forWebSocket);
}
static RealCall newRealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
// Safely publish the Call instance to the EventListener.
RealCall call = new RealCall(client, originalRequest, forWebSocket);
call.eventListener = client.eventListenerFactory().create(call);
return call;
}
以上代码描述了OkHttpClient生成RealCall的流程。
5. RealCall.execute方法
RealCall.execute是请求流程真正开始执行的入口,下面我们来分析下代码:
@Override public Response execute() throws IOException {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
captureCallStackTrace();
eventListener.callStart(this);
try {
client.dispatcher().executed(this);
Response result = getResponseWithInterceptorChain();
if (result == null) throw new IOException("Canceled");
return result;
} catch (IOException e) {
eventListener.callFailed(this, e);
throw e;
} finally {
client.dispatcher().finished(this);
}
}
这段代码主要做了下面的事情:
检查该请求是否已经执行,如果已经执行则直接抛出异常。每个call只能执行一次,如果需要同样的请求,可以调用clone方法克隆。
事件开始回调。
利用client.dispatcher().executed(this)来进行状态标记(标记该请求正在执行中),dispatcher是刚才看到的OkHttpClient.Builder 的成员之一。
调用getResponseWithInterceptorChain()函数获取HTTP返回结果,从函数名可以看出,这一步还会进行一系列“拦截”操作。
出现异常时回调通知。
最后通知分发器处理结束。
6. RealCall.getResponseWithInterceptorChain
该接口是真正发起网络请求,解析返回处理结果。
关于代码中出现的各种拦截器,文章后面会进行详细分析和描述。
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
// 构造拦截器栈
List<Interceptor> interceptors = new ArrayList<>();
interceptors.addAll(client.interceptors());
interceptors.add(retryAndFollowUpInterceptor);
interceptors.add(new BridgeInterceptor(client.cookieJar()));
interceptors.add(new CacheInterceptor(client.internalCache()));
interceptors.add(new ConnectInterceptor(client));
if (!forWebSocket) {
interceptors.addAll(client.networkInterceptors());
}
interceptors.add(new CallServerInterceptor(forWebSocket));
Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
originalRequest, this, eventListener, client.connectTimeoutMillis(),
client.readTimeoutMillis(), client.writeTimeoutMillis());
return chain.proceed(originalRequest);
}
- 添加拦截器
interceptors.addAll(client.interceptors());
添加client配置的拦截器,默认值为空。
可根据需要添加自定义的拦截器(比如日志拦截器,拦截器的实现我们可以参照OkHttp内置的拦截器),注意添加的自定义拦截器的优先级较高。
- 添加重试拦截器
interceptors.add(retryAndFollowUpInterceptor);
retryAndFollowUpInterceptor为负责失败重试、重定向的拦截器,创建RealCall时生成的。
- 添加桥接拦截器
interceptors.add(new BridgeInterceptor(client.cookieJar()));
该拦截器负责将用户构造的请求转换为发送到服务器的请求,把服务器的响应转换为用户响应。
- 添加缓存拦截器
interceptors.add(new CacheInterceptor(client.internalCache()));
该拦截器负责读取缓存、更新缓存内容。
- 添加连接拦截器
interceptors.add(new ConnectInterceptor(client));
该拦截器负责与服务器建立连接。
- 添加网络拦截器
if (!forWebSocket) {
interceptors.addAll(client.networkInterceptors());
}
该拦截器在由client配置,默认为空,可根据需要进行配置。
- 添加请求拦截器
interceptors.add(new CallServerInterceptor(forWebSocket));
该拦截器负责向服务器发送请求数据、从服务器读取响应数据。
- 链式处理请求
return chain.proceed(originalRequest);
开启链式处理请求,并返回结果。
请求处理分析
在上述的章节中,我们已经分析了请求是如何构造的,以及其中牵涉到的拦截器和实际处理请求的一些对象,接下来我们将紧接上节内容分析OkHttp链式处理流程,让你对请求的处理过程有一个更深层次的了解。
1.RealInterceptorChain
先看下拦截器链处理流程代码:
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException {
// 判断拦截器是否在拦截器栈内
if (index >= interceptors.size()) throw new AssertionError();
calls++;
// If we already have a stream, confirm that the incoming request will use it.
// 如果存在了流,那么确保即将来的reuquest会使用它,而不是重新请求一次。
if (this.httpCodec != null && !this.connection.supportsUrl(request.url())) {
throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
+ " must retain the same host and port");
}
// If we already have a stream, confirm that this is the only call to chain.proceed().
// 如果已经存在流,那么确保proceed处理的是唯一的call
if (this.httpCodec != null && calls > 1) {
throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
+ " must call proceed() exactly once");
}
// Call the next interceptor in the chain.
// 根据责任链模式构造下一个拦截器链
RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
writeTimeout);
// 获取当前处理请求的拦截器
Interceptor interceptor = interceptors.get(index);
// 拦截请求,并处理请求
Response response = interceptor.intercept(next);
// Confirm that the next interceptor made its required call to chain.proceed().
if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) {
throw new IllegalStateException("network interceptor " + interceptor
+ " must call proceed() exactly once");
}
// Confirm that the intercepted response isn't null.
// 确保返回结果不为空
if (response == null) {
throw new NullPointerException("interceptor " + interceptor + " returned null");
}
// 确保返回结果的内容不为空
if (response.body() == null) {
throw new IllegalStateException(
"interceptor " + interceptor + " returned a response with no body");
}
return response;
}
这段代码不长,却是OkHttp的核心所在,也是链式请求的经典代码(可参考责任链模式的描述)。
至于这段代码是什么意思,代码里的注释已经写的很清楚了,在此就不再赘述了,我们主要分析下链式调用流程。
// Call the next interceptor in the chain.
// 根据责任链模式构造下一个拦截器链
RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
writeTimeout);
Interceptor interceptor = interceptors.get(index);
Response response = interceptor.intercept(next);
- 实例化下一个拦截器的Chain。
- 获取当前拦截器。
- 调用当前拦截器的intercept方法处理请求,并将下一个拦截器的chain交给当前拦截器持有。
2.RetryAndFollowUpInterceptor
根据前面的分析(生成RealCall的过程),除了OkHttpClient自定义设置的拦截器,该拦截器是首先被调用的拦截器。
该拦截器负责失败重试及需要时的重定向处理,如果call被取消它可能会抛出IO异常。
看下它是如何处理请求的:
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Call call = realChain.call();
EventListener eventListener = realChain.eventListener();
streamAllocation = new StreamAllocation(client.connectionPool(), createAddress(request.url()),
call, eventListener, callStackTrace);
int followUpCount = 0;
Response priorResponse = null;
while (true) {
if (canceled) {
streamAllocation.release();
throw new IOException("Canceled");
}
Response response;
boolean releaseConnection = true;
try {
//1.这是核心代码,直接调用了下一个拦截器处理,因为该拦截器不会直接返回Response
response = realChain.proceed(request, streamAllocation, null, null);
releaseConnection = false;
} catch (RouteException e) {
// The attempt to connect via a route failed. The request will not have been sent.
//请求线路失败的情况,请求将不会发送
if (!recover(e.getLastConnectException(), false, request)) {
throw e.getLastConnectException();
}
releaseConnection = false;
continue;
} catch (IOException e) {
// An attempt to communicate with a server failed. The request may have been sent.
// 与服务器尝试通讯失败,那么请求可能不会被发送
boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
if (!recover(e, requestSendStarted, request)) throw e;
releaseConnection = false;
continue;
} finally {
// We're throwing an unchecked exception. Release any resources.
// 抛出未检查的异常,释放资源
if (releaseConnection) {
streamAllocation.streamFailed(null);
streamAllocation.release();
}
}
// Attach the prior response if it exists. Such responses never have a body.
if (priorResponse != null) {
response = response.newBuilder()
.priorResponse(priorResponse.newBuilder()
.body(null)
.build())
.build();
}
Request followUp = followUpRequest(response);
if (followUp == null) {
if (!forWebSocket) {
streamAllocation.release();
}
return response;
}
closeQuietly(response.body());
if (++followUpCount > MAX_FOLLOW_UPS) {
streamAllocation.release();
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}
if (followUp.body() instanceof UnrepeatableRequestBody) {
streamAllocation.release();
throw new HttpRetryException("Cannot retry streamed HTTP body", response.code());
}
if (!sameConnection(response, followUp.url())) {
streamAllocation.release();
streamAllocation = new StreamAllocation(client.connectionPool(),
createAddress(followUp.url()), call, eventListener, callStackTrace);
} else if (streamAllocation.codec() != null) {
throw new IllegalStateException("Closing the body of " + response
+ " didn't close its backing stream. Bad interceptor?");
}
request = followUp;
priorResponse = response;
}
}
- 核心代码
response = realChain.proceed(request, streamAllocation, null, null);
- 后续请求构造
Request followUp = followUpRequest(response);
根据返回结果码来构造接下来需要进行的请求,这也是重试机制的体现。
如果followUp为空,则不再进行重试。
3.BridgeInterceptor
该拦截器负责将用户构造的请求转换为发送到服务器的请求、把服务器返回的响应转换为用户友好的响应 。
@Override public Response intercept(Chain chain) throws IOException {
Request userRequest = chain.request();
Request.Builder requestBuilder = userRequest.newBuilder();
//检查用户的request,并转换为合适的服务器请求
RequestBody body = userRequest.body();
if (body != null) {
MediaType contentType = body.contentType();
if (contentType != null) {
requestBuilder.header("Content-Type", contentType.toString());
}
long contentLength = body.contentLength();
if (contentLength != -1) {
requestBuilder.header("Content-Length", Long.toString(contentLength));
requestBuilder.removeHeader("Transfer-Encoding");
} else {
requestBuilder.header("Transfer-Encoding", "chunked");
requestBuilder.removeHeader("Content-Length");
}
}
if (userRequest.header("Host") == null) {
requestBuilder.header("Host", hostHeader(userRequest.url(), false));
}
if (userRequest.header("Connection") == null) {
requestBuilder.header("Connection", "Keep-Alive");
}
// If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing
// the transfer stream.
boolean transparentGzip = false;
if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
transparentGzip = true;
requestBuilder.header("Accept-Encoding", "gzip");
}
List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
if (!cookies.isEmpty()) {
requestBuilder.header("Cookie", cookieHeader(cookies));
}
if (userRequest.header("User-Agent") == null) {
requestBuilder.header("User-Agent", Version.userAgent());
}
//将响应转换为合适的Response
Response networkResponse = chain.proceed(requestBuilder.build());
HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
Response.Builder responseBuilder = networkResponse.newBuilder()
.request(userRequest);
if (transparentGzip
&& "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))
&& HttpHeaders.hasBody(networkResponse)) {
GzipSource responseBody = new GzipSource(networkResponse.body().source());
Headers strippedHeaders = networkResponse.headers().newBuilder()
.removeAll("Content-Encoding")
.removeAll("Content-Length")
.build();
responseBuilder.headers(strippedHeaders);
String contentType = networkResponse.header("Content-Type");
responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
}
return responseBuilder.build();
}
4.CacheInterceptor
这是OkHttp中一个很重要的拦截器,也是我们通常所说的网络请求缓存,它能在允许使用缓存的情况下,快速返回已经缓存的请求结果。
@Override public Response intercept(Chain chain) throws IOException {
//读取缓存
Response cacheCandidate = cache != null
? cache.get(chain.request())
: null;
long now = System.currentTimeMillis();
//根据缓存请求生成对应的策略
CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
Request networkRequest = strategy.networkRequest;
Response cacheResponse = strategy.cacheResponse;
if (cache != null) {
cache.trackResponse(strategy);
}
//存在缓存,但是缓存不允许,那么就关掉缓存
if (cacheCandidate != null && cacheResponse == null) {
closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
}
// If we're forbidden from using the network and the cache is insufficient, fail.
//如果我们被禁止使用网络,且缓存为空,那么直接返回错误
if (networkRequest == null && cacheResponse == null) {
return new Response.Builder()
.request(chain.request())
.protocol(Protocol.HTTP_1_1)
.code(504)
.message("Unsatisfiable Request (only-if-cached)")
.body(Util.EMPTY_RESPONSE)
.sentRequestAtMillis(-1L)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
}
// If we don't need the network, we're done.
// 如果我们不需要使用网络,那么直接返回缓存
if (networkRequest == null) {
return cacheResponse.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.build();
}
// 不存在缓存的情况下,直接调用下个拦截器进行处理
Response networkResponse = null;
try {
networkResponse = chain.proceed(networkRequest);
} finally {
// If we're crashing on I/O or otherwise, don't leak the cache body.
// 如果我们发生了IO异常,那么我们就关掉缓存,防止泄露
if (networkResponse == null && cacheCandidate != null) {
closeQuietly(cacheCandidate.body());
}
}
// If we have a cache response too, then we're doing a conditional get.
//如果我们存在缓存,且网络请求的结果信息未改变
if (cacheResponse != null) {
if (networkResponse.code() == HTTP_NOT_MODIFIED) {
Response response = cacheResponse.newBuilder()
.headers(combine(cacheResponse.headers(), networkResponse.headers()))
.sentRequestAtMillis(networkResponse.sentRequestAtMillis())
.receivedResponseAtMillis(networkResponse.receivedResponseAtMillis())
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
networkResponse.body().close();
// Update the cache after combining headers but before stripping the
// Content-Encoding header (as performed by initContentStream()).
// 更新缓存内容
cache.trackConditionalCacheHit();
cache.update(cacheResponse, response);
return response;
} else {
closeQuietly(cacheResponse.body());
}
}
Response response = networkResponse.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
//将未缓存过的内容进行缓存处理
if (cache != null) {
if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
// Offer this request to the cache.
CacheRequest cacheRequest = cache.put(response);
return cacheWritingResponse(cacheRequest, response);
}
//对于一些特殊的请求方法,是无法进行缓存的;如果存在则进行移除
//不可缓存的请求方法:POST|PATCH|PUT|DELETE|MOVE
if (HttpMethod.invalidatesCache(networkRequest.method()))
{
try {
cache.remove(networkRequest);
} catch (IOException ignored) {
// The cache cannot be written.
}
}
}
return response;
}
5. ConnectInterceptor
该拦截器主要负责建立与服务器的连接,为后续处理返回结果做铺垫。
@Override public Response intercept(Chain chain) throws IOException {
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Request request = realChain.request();
StreamAllocation streamAllocation = realChain.streamAllocation();
// We need the network to satisfy this request. Possibly for validating a conditional GET.
boolean doExtensiveHealthChecks = !request.method().equals("GET");
HttpCodec httpCodec = streamAllocation.newStream(client, chain, doExtensiveHealthChecks);
RealConnection connection = streamAllocation.connection();
return realChain.proceed(request, streamAllocation, httpCodec, connection);
}
代码很简单,建立连接其实核心就是创建了一个HttpCodec 实例,HttpCodec的主要作用就是:Encodes HTTP requests and decodes HTTP responses。
HttpCodec是一个接口,它的实现类有两个,分别为:
- Http1Codec
用于发送HTTP/1.1消息的连接。 - Http2Codec
用于处理HTTP/2消息。
5.NetworkInterceptors
配置OkHttpClient时设置的 NetworkInterceptors。
6.CallServerInterceptor
该拦截器主要是向服务器发送请求。
@Override public Response intercept(Chain chain) throws IOException {
RealInterceptorChain realChain = (RealInterceptorChain) chain;
HttpCodec httpCodec = realChain.httpStream();
StreamAllocation streamAllocation = realChain.streamAllocation();
RealConnection connection = (RealConnection) realChain.connection();
Request request = realChain.request();
long sentRequestMillis = System.currentTimeMillis();
realChain.eventListener().requestHeadersStart(realChain.call());
httpCodec.writeRequestHeaders(request);
realChain.eventListener().requestHeadersEnd(realChain.call(), request);
Response.Builder responseBuilder = null;
if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
// If there's a "Expect: 100-continue" header on the request, wait for a "HTTP/1.1 100
// Continue" response before transmitting the request body. If we don't get that, return
// what we did get (such as a 4xx response) without ever transmitting the request body.
if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
httpCodec.flushRequest();
realChain.eventListener().responseHeadersStart(realChain.call());
responseBuilder = httpCodec.readResponseHeaders(true);
}
if (responseBuilder == null) {
// Write the request body if the "Expect: 100-continue" expectation was met.
realChain.eventListener().requestBodyStart(realChain.call());
long contentLength = request.body().contentLength();
CountingSink requestBodyOut =
new CountingSink(httpCodec.createRequestBody(request, contentLength));
BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);
request.body().writeTo(bufferedRequestBody);
bufferedRequestBody.close();
realChain.eventListener()
.requestBodyEnd(realChain.call(), requestBodyOut.successfulCount);
} else if (!connection.isMultiplexed()) {
// If the "Expect: 100-continue" expectation wasn't met, prevent the HTTP/1 connection
// from being reused. Otherwise we're still obligated to transmit the request body to
// leave the connection in a consistent state.
streamAllocation.noNewStreams();
}
}
httpCodec.finishRequest();
if (responseBuilder == null) {
realChain.eventListener().responseHeadersStart(realChain.call());
//此处是发起网络请求并获得返回结果
responseBuilder = httpCodec.readResponseHeaders(false);
}
Response response = responseBuilder
.request(request)
.handshake(streamAllocation.connection().handshake())
.sentRequestAtMillis(sentRequestMillis)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
realChain.eventListener()
.responseHeadersEnd(realChain.call(), response);
int code = response.code();
if (forWebSocket && code == 101) {
// Connection is upgrading, but we need to ensure interceptors see a non-null response body.
response = response.newBuilder()
.body(Util.EMPTY_RESPONSE)
.build();
} else {
response = response.newBuilder()
.body(httpCodec.openResponseBody(response))
.build();
}
if ("close".equalsIgnoreCase(response.request().header("Connection"))
|| "close".equalsIgnoreCase(response.header("Connection"))) {
streamAllocation.noNewStreams();
}
if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
throw new ProtocolException(
"HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
}
return response;
}
2.异步请求
示例
/**
* 异步get请求
*
* @param url 请求的url
* @param callback 回调接口
*/
public static void asyncGet(String url, Callback callback) {
//1.实例化一个OkHttpClient实例
OkHttpClient client = new OkHttpClient();
//2.构造一个Request请求
//这几乎是最简单的请求构造方法
Request request = new Request.Builder()
.url(url)
.build();
//3.根据request生成call请求
Call call = client.newCall(request);
//4.调用异步处理方法
//Callback是为了演示如何使用它,可直接使用传入的callback
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
boolean isSuccessful=response.isSuccessful();
if(isSuccessful){
System.out.println(response.body().string());
}else{
throw new IOException("Unexpected code:"+response.code());
}
}
});
}
在以上代码中1、2、3都与同步请求的过程相同,在此不再赘述。接下来,我们从call.enqueue(new Callback() )分析异步请求的过程,下面我们先来看RealCall的enqueue方法。
@Override public void enqueue(Callback responseCallback) {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
captureCallStackTrace();
eventListener.callStart(this);
client.dispatcher().enqueue(new AsyncCall(responseCallback));
}
调用了Dispatcher的enqueue方法,我们接着往下看:
synchronized void enqueue(AsyncCall call) {
if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
runningAsyncCalls.add(call);
executorService().execute(call);
} else {
readyAsyncCalls.add(call);
}
}
如果中的runningAsynCalls的数量小于最大的请求数(64),且call占用的host小于最大数量(5),那么就将call加入到runningAsyncCalls中利用线程池执行call;否者将call加入到readyAsyncCalls(后续会按顺序执行)。
下面是runningAsyncCalls与readyAsyncCalls的定义:
/** Ready async calls in the order they'll be run. */
private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>();
/** Running asynchronous calls. Includes canceled calls that haven't finished yet. */
private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();
那么AsyncCall 到底是什么呢,我们来看AsyncCall 的定义:
final class AsyncCall extends NamedRunnable {
private final Callback responseCallback;
AsyncCall(Callback responseCallback) {
super("OkHttp %s", redactedUrl());
this.responseCallback = responseCallback;
}
String host() {
return originalRequest.url().host();
}
Request request() {
return originalRequest;
}
RealCall get() {
return RealCall.this;
}
@Override protected void execute() {
boolean signalledCallback = false;
try {
//核心代码是这一句
Response response = getResponseWithInterceptorChain();
if (retryAndFollowUpInterceptor.isCanceled()) {
signalledCallback = true;
responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
} else {
signalledCallback = true;
responseCallback.onResponse(RealCall.this, response);
}
} catch (IOException e) {
if (signalledCallback) {
// Do not signal the callback twice!
Platform.get().log(INFO, "Callback failure for " + toLoggableString(), e);
} else {
eventListener.callFailed(RealCall.this, e);
responseCallback.onFailure(RealCall.this, e);
}
} finally {
client.dispatcher().finished(this);
}
}
}
原来AsyncCall是一个Runnable对象,它的核心代码就是这一句:
Response response = getResponseWithInterceptorChain();
我们已经在上一节的篇章中分析过该语句的执行过程,这样异步任务也同样通过了interceptor,剩下的流程就和上面一样了。
3.结束语
很多框架结构都没有我们想象中的那么难,只要静下心来分析,相信大家都能理解其内部的流程和机制。希望大家在以后的工作学习中也能多思考、多看,早日写出自己的牛逼框架。