上篇文章对比了同步与异步请求流程的区别,最终都是通过getResponseWithInterceptorChain()方法返回得到响应,这个方法涉及到了okhttp的核心,也就是拦截器,接下来我们了解一下其工作原理。
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);
}
在getResponseWithInterceptorChain()方法中,依次加入自定义interceptors、RetryAndFollowUpInterceptor、BridgeInterceptor、CacheInterceptor、ConnectInterceptor、自定义NetWorkInterceptors、CallServerInterceptor,其中自定义interceptors和NetWorkInterceptors需要自己设置(默认没有),知道了自定义拦截器的调用顺序我们就能更好的发挥他们的作用了。然后生成拦截器链,拦截器链的具体实现是RealInterceptorChain类,持有整个拦截器链:包含所有应用拦截器,所有网络拦截器,最终的网络调用者。
RealInterceptorChain类
public final class RealInterceptorChain implements Interceptor.Chain {
private final List<Interceptor> interceptors;
private final StreamAllocation streamAllocation;
private final HttpCodec httpCodec;
private final RealConnection connection;
private final int index;
private final Request request;
private final Call call;
private final EventListener eventListener;
private final int connectTimeout;
private final int readTimeout;
private final int writeTimeout;
private int calls;
public RealInterceptorChain(List<Interceptor> interceptors, StreamAllocation streamAllocation,
HttpCodec httpCodec, RealConnection connection, int index, Request request, Call call,
EventListener eventListener, int connectTimeout, int readTimeout, int writeTimeout) {
this.interceptors = interceptors;
this.connection = connection;
this.streamAllocation = streamAllocation;
this.httpCodec = httpCodec;
this.index = index;
this.request = request;
this.call = call;
this.eventListener = eventListener;
this.connectTimeout = connectTimeout;
this.readTimeout = readTimeout;
this.writeTimeout = writeTimeout;
}
}
interceptors:存放拦截器的列表。
index:表示当前拦截器的索引。
StreamAllocation称之流的桥梁,它负责为一次 "请求"寻找 "连接"并建立"流",从而完成远程通信。所以说StreamAllocation与"请求"、"连接"、"流"都有关。
HttpCodec是对HTTP协议操作的抽象,有Http1Codec和Http2Codec两个实现,分别对应HTTP/1.1和HTTP/2版本。在Http1Codec中,它利用Okio对Socket的读写操作进行封装,让我们更高效的进行IO操作。HttpCodec利用RealConnection创建。
RealConnection是Connection的实现类,代表着链接socket的链路,如果拥有了一个RealConnection就代表了我们已经跟服务器有了一条通信链路,这个类里面实现了三次握手等;
EventListener:事件监听器,继承该类以监视应用程序Http调用的数量、大小和持续事件。
proceed()
主要看一下它的proceed()方法:
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.
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().
if (this.httpCodec != null && calls > 1) {
throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
+ " must call proceed() exactly once");
}
// 创建索引从 index+1 开始的拦截器链
RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
writeTimeout);
// 获取索引为 index 的拦截器
Interceptor interceptor = interceptors.get(index);
// 执行索引为 index 的拦截器的 intercept方法
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;
}
这里有一个 index参数,代表拦截器当前拦截器的索引。proceed()方法中经过一些判断后新建一个索引从 index+1开始的新的拦截器链(index一开始为0),也就是实例化一个新的拦截器链,新的拦截器链包含除了当前拦截器之后的所有拦截器,然后调用索引为index的拦截器的intercept(拦截器链)方法,传入刚创建的拦截器链,该拦截器执行完后会调用传入的拦截器链,执行索引为index+1的拦截器,依次类推直到得到响应,。
RetryAndFollowUpInterceptor
RetryAndFollowUpInterceptor拦截器,当请求失败时恢复请求,根据需要进行重定向,在Call被取消时抛出IOException异常。
@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");
}
//否则调用拦截器链的proceed方法调用剩下的拦截器
Response response;
boolean releaseConnection = true;
try {
//将 streamAllocation传递进去
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();
}
//根据响应创建重定向请求,如果不需要重定向,则followUpRequest返回空,反之返回新的请求
Request followUp = followUpRequest(response);
// 不需要重定向则返回当前响应
if (followUp == null) {
if (!forWebSocket) {
// 如果不是使用 websocket(即长连接)协议,则释放 streamAllocation
streamAllocation.release();
}
//这里直接返回当前响应
return response;
}
/**
* 下面部分是需要重定向才执行的代码,也就是上面的if语句为false的时候
*/
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,将当前的响应赋予 priorResponse
request = followUp;
priorResponse = response;
}
}
1、如果请求取消了,则释放流并抛出异常。
2、否则调用拦截器链的proceed方法调用剩下的拦截器,如果获取响应失败,如果是路由或者连接异常,则尝试恢复。
3、得到响应后,调用 followUpRequest(response)方法, followUpRequest()方法根据响应码(ResponseCode)判断是否需要重定向,需要则返回新的 Request ,计算要发出的 HTTP请求,添加验证头、重定向或者处理用户端超时。
4、如果不需要重定向(followUpRequest方法返回null)则直接返回响应。
5、如果需要重定向则进入 while循环。如果重定向的url和之前的请求的url是用一个,则使用同一个连接,否则重新创建连接。
BridgeInterceptor
负责把用户构造的 Request 转换为发送给服务器的网络请求(添加头信息等),然后发起网络请求;把服务器返回的响应转换为 Response对象。
@Override public Response intercept(Chain chain) throws IOException {
Request userRequest = chain.request();
Request.Builder requestBuilder = userRequest.newBuilder();
RequestBody body = userRequest.body();
if (body != null) {
MediaType contentType = body.contentType();
// 设置 Content-Type
if (contentType != null) {
requestBuilder.header("Content-Type", contentType.toString());
}
long contentLength = body.contentLength();
//Content-Length和Transfer-Encoding互斥
if (contentLength != -1) {
requestBuilder.header("Content-Length", Long.toString(contentLength));
requestBuilder.removeHeader("Transfer-Encoding");
} else {
requestBuilder.header("Transfer-Encoding", "chunked");
requestBuilder.removeHeader("Content-Length");
}
}
// 设置 Host
if (userRequest.header("Host") == null) {
requestBuilder.header("Host", hostHeader(userRequest.url(), false));
}
// 设置 Connection
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 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")//Content-Encoding、Content-Length不能用于Gzip压缩
.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();
}
1、如果存在请求体,在请求头中添加Content-Type、Content-Length,如果请求体长度为-1,添加Transfer-Encoding(分块传输)添加Host、Connection(持久连接)、gzip压缩、Cookie等。
2、继续调用拦截器链的proceed方法来调用剩下的拦截器的intercept方法。得到响应后,根据需要保存Cookie,如果请求进行了压缩,则解压,等。返回响应。
CacheInterceptor
负责读取缓存以及更新缓存。
先了解一下缓存,缓存的大致流程如下:
服务器收到请求时,会在200 OK中回送该资源的Last-Modified和ETag头(服务器支持缓存的情况下才会有这两个头哦),客户端将该资源保存在cache中,并记录这两个属性。当客户端需要发送相同的请求时,根据缓存中资源头信息的Date + Cache-control来判断是否缓存过期,如果过期了,会在请求头中携带If-Modified-Since和If-None-Match两个头。两个头的值分别是上一次响应中Last-Modified和ETag头的值。服务器通过这两个头判断本地资源未发生变化,客户端不需要重新下载,返回304响应(代表客户可以使用原来缓存的文档)。具体可参考https://blog.csdn.net/chunqiuwei/article/details/73224494
接下来看一下intercept方法:
@Override public Response intercept(Chain chain) throws IOException {
//如果配置了缓存:优先从缓存中读取Response
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.
}
//如果根据缓存策略strategy禁止使用网络,并且缓存无效,直接返回空的Response
// 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();
}
//如果根据缓存策略strategy禁止使用网络,且有缓存则直接使用缓存
// 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.
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) {
//并且服务器返回304状态码(说明缓存还没过期或服务器资源没修改)
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);
}
if (HttpMethod.invalidatesCache(networkRequest.method())) {
try {
cache.remove(networkRequest);
} catch (IOException ignored) {
// The cache cannot be written.
}
}
}
return response;
}
如果没有对OkHttpClient设置cache,则CacheInterceptor构造时的cache为空,也就是没有缓存。
如果有cache的话,从用户的cache中取得当前请求的缓存cacheCandidate,更具当前请求和cacheCandidate创建缓存策略CacheStrategy,该策略通过某种规则来判断缓存是否有效;
1、如果缓存策略禁止使用网络(networkRequest==null),并且缓存无效(cacheResponse==null),直接返回空response
2、如果缓存策略禁止使用网络,且有缓存则直接使用缓存
3、缓存需要使用网络,则调用chain.proceed()执行下一个拦截器,得到响应后,如果本地有缓存且服务器返回304状态码(说明缓存没过期或服务器资源没修改),则返回缓存数据,如果服务器资源已修改或者本地没有缓存,则使用网络响应返回最新数据,并将最新数据缓存起来。
那networkRequest和cacheResponse又是怎么样决定的呢?CacheStrategy是由CacheStrategy.Factory调用get方法得到的,get方法又调用getCandidate方法:
/** Returns a strategy to use assuming the request can use the network. */
private CacheStrategy getCandidate() {
// No cached response.
if (cacheResponse == null) {
//没有缓存,使用网络请求
return new CacheStrategy(request, null);
}
//请求为https,但没有握手,使用网络请求
// Drop the cached response if it's missing a required handshake.
if (request.isHttps() && cacheResponse.handshake() == null) {
return new CacheStrategy(request, null);
}
//响应是不可缓存的,使用网络请求
// If this response shouldn't have been stored, it should never be used
// as a response source. This check should be redundant as long as the
// persistence store is well-behaved and the rules are constant.
if (!isCacheable(cacheResponse, request)) {
return new CacheStrategy(request, null);
}
//请求头包含nocache或者包含If-Modified-Since或者If-None-Match(意味着本地缓存过期)
//需要服务器验证本地缓存是否能继续使用,使用网络请求
CacheControl requestCaching = request.cacheControl();
if (requestCaching.noCache() || hasConditions(request)) {
return new CacheStrategy(request, null);
}
CacheControl responseCaching = cacheResponse.cacheControl();
//强制使用缓存
if (responseCaching.immutable()) {
return new CacheStrategy(null, cacheResponse);
}
...
}
ConnectInterceptor
连接层是一个比较复杂的层级,它实现了网络协议、内部拦截器、安全性认证、连接与连接池等功能,
主要作用是打开了与服务器的链接,正式开启了网络请求
@Override public Response intercept(Chain chain) throws IOException {
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Request request = realChain.request();
// 从拦截器链中获取 StreamAllocation
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
RealConnection connection = streamAllocation.connection();
return realChain.proceed(request, streamAllocation, httpCodec, connection);
}
可以看到从拦截器链对象上获取StreamAllocation对象,一开始在 RealCall 对象中初始化拦截器链的时候传入的StreamAllocation是null,真正的StreamAllocation是在RetryAndFollowUpInterceptor的intercept方法中传入的,如下:
@Override public Response intercept(Chain chain) throws IOException {
....
streamAllocation = new StreamAllocation(client.connectionPool(), createAddress(request.url()),
call, eventListener, callStackTrace);
....
response = realChain.proceed(request, streamAllocation, null, null);
....
}
1、这里 ConnectionInterceptor中 streamAllocation的主要作用是从OkHttpClient的连接池 ConnectionPool对象(连接池持有一个队列 ArrayDeque 作为缓存池,存放 RealConnection,主要实现连接的复用)中获取一个或者创建一个 RealConnection放入缓存池( RealConnection 是 Connection 的子类,主要实现连接的建立等工作)。
2、调用 RealConnection的 connect()方法打开一个 Socket连接到目标 Server,然后用 RealConnection对象 生成一个 HttpCodec 用于下一个拦截器的输入输出操作,为最终的请求做准备。
CallServerInterceptor
上面的拦截器ConnectInterceptor已经帮我们把通道建立好了,所以在这个CallServerInterceptor拦截器里面,我们的任务就是发送相关的数据。
@Override public Response intercept(Chain chain) throws IOException {
RealInterceptorChain realChain = (RealInterceptorChain) chain;
// 获取 httpCodec,也就是上一个拦截器生成的对象
HttpCodec httpCodec = realChain.httpStream();
// 获取 StreamAllocation 对象
StreamAllocation streamAllocation = realChain.streamAllocation();
// 获取 RealConnection 对象,也是上一个拦截器生成的
RealConnection connection = (RealConnection) realChain.connection();
// 获取 Request 对象
Request request = realChain.request();
long sentRequestMillis = System.currentTimeMillis();
realChain.eventListener().requestHeadersStart(realChain.call());
// 发送请求头 Header
httpCodec.writeRequestHeaders(request);
realChain.eventListener().requestHeadersEnd(realChain.call(), request);
Response.Builder responseBuilder = null;
//如果当前request请求有请求体
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.
//询问Server服务器是否接受请求body(基于请求头部)
if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
httpCodec.flushRequest();
realChain.eventListener().responseHeadersStart(realChain.call());
// 构建 responseBuilder 对象,先读取响应头 Header
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 {
// 获取响应体 body
response = response.newBuilder()
.body(httpCodec.openResponseBody(response))
.build();
}
//如果服务器不支持持久连接,则禁止在此连接上创建新的stream
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;
}
获取HttpCodec对象并写入请求头信息,接着判断是否需要写入请求体,最后读取响应并返回响应。
得到响应后,各个拦截器又对响应做了处理。
最后我们看一下ResponseBody类的string()方法:
public final String string() throws IOException {
BufferedSource source = source();
try {
Charset charset = Util.bomAwareCharset(source, charset());
return source.readString(charset);
} finally {
Util.closeQuietly(source);
}
}
可以看到,通过调用source.readString来读取服务器的数据,但是方法最后调用closeQuietly关闭了请求的InputStream输入流,所以string()方法只能调用一次,多次调用会报错。
拦截器的分析到这里结束,其中还有很多细节需要了解,可以多看看更加深入的文章!
参考文章:
https://blog.piasy.com/2016/07/11/Understand-OkHttp/
https://blog.csdn.net/qq_19431333/article/details/53207220
https://blog.csdn.net/u012881042/article/details/79759203
https://blog.csdn.net/json_it/article/details/78404010
https://blog.csdn.net/chunqiuwei/article/details/73350657