okhttp

okhttp源码分析

okhttp有两种创建实例的方式,一种是直接new,另一种是通过他的builder,我们就直接通过builder来进行创建,先用最简单的builder来创建。

1
2
3
4
5
OkHttpClient.Builder client = new OkHttpClient.Builder();
Request request = new Request.Builder()
.url("https://api.github.com/")
.build();
client.build().newCall(request).execute();

builder里面初始化了okhttp需要的类,我们可以先不去管他,到用的时候再去这里找。

之后我们来看Request的builder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public final class Request {
// buider的构造函数就做了两个事情
// 一个是将method默认为‘get’
// 创建一个Headers.Builder
public Builder() {
this.method = "GET";
this.headers = new Headers.Builder();
}
}
// Header.Builder没有构造函数,
// 但是他会在类加载的时候创建一个List
public final class Headers {
public static final class Builder {
// 这个方法直接要了20个长度的内存
final List<String> namesAndValues = new ArrayList<>(20);
}
}

url我们就不看了,直接看build()吧。

1
2
3
4
5
6
7
8
9
10
11
public final class Request {
public static final class Builder {
public Request build() {
if (url == null) throw new IllegalStateException("url == null");
// Request的构造函数就是把Request创建好的实例放到Request中。
// 在构造函数中把Header.Buider给build好
// Header的构造函数也就是把Builder创建的实例放到Header中
return new Request(this);
}
}
}

看完Request,就可以看OkhttpClient,OkhttpClient.Builder还是和之前的builder一样,所以我们直接看newCall(request)

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
/**
* Prepares the {@code request} to be executed at some point in the future.
*/
public class OkHttpClient implements Cloneable, Call.Factory, WebSocket.Factory {
@Override public Call newCall(Request request) {
return RealCall.newRealCall(this, request, false /* for web socket */);
}
}
final class RealCall implements Call {
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;
}
private RealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
this.client = client;
this.originalRequest = originalRequest;
this.forWebSocket = forWebSocket;
// 这个Interceptor之后会用到。
this.retryAndFollowUpInterceptor = new RetryAndFollowUpInterceptor(client, forWebSocket);
// timeout是okio部分,所以我们这里先不分析
this.timeout = new AsyncTimeout() {
@Override protected void timedOut() {
cancel();
}
};
this.timeout.timeout(client.callTimeoutMillis(), MILLISECONDS);
}
}

之后我们要分析execute(),okhttp有两个执行的方法,execute()enqueue(),前一个是同步的,后一个是异步的。我们先来分析execute()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
final class RealCall implements Call {
@Override public Response execute() throws IOException {
...
// eventListener是用来给到用户监听的。
eventListener.callStart(this);
try {
// 这个方法是将这次请求纪录下来,说明他已经在running了
client.dispatcher().executed(this);
// 接下来分析这个方法
Response result = getResponseWithInterceptorChain();
if (result == null) throw new IOException("Canceled");
return result;
} catch (IOException e) {
e = timeoutExit(e);
eventListener.callFailed(this, e);
throw e;
} finally {
client.dispatcher().finished(this);
}
}
}

接下来分析getResponseWithInterceptorChain(),这个方法是开始进入主流程的入口。

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
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));
// forWebSocket在调用newRealCall方法时传入的false
// 所以networkInterceptors会加入到interceptors
if (!forWebSocket) {
interceptors.addAll(client.networkInterceptors());
}
interceptors.add(new CallServerInterceptor(forWebSocket));
// 这里总结一下,搞清楚interceptors这个列表里面有什么东西
// [retryAndFollowUpInterceptor, BridgeInterceptor,
// CacheInterceptor, ConnectInterceptor,
// networkInterceptors, CallServerInterceptor]
// 之后每个Request都会进入到这几个Interceptor,然后返回出Response。
// 这里只是做一些常规的初始化。
Interceptor.Chain chain = new RealInterceptorChain(
interceptors, null, null,
null, 0, originalRequest,
this, eventListener, client.connectTimeoutMillis(),
client.readTimeoutMillis(), client.writeTimeoutMillis());
// 接下来我们就来分析这个方法
return chain.proceed(originalRequest);
}

接下来我们来分析RealInterceptorChain.proceed(),proceed里面还有一个重载的方法,我们直接看看传入了什么值。

1
2
3
4
5
6
@Override public Response proceed(Request request) throws IOException {
return proceed(request,
streamAllocation /* null */,
httpCodec /* null */,
connection /* null */);
}

除了request,其他参数都是null,那么我们就可以真正分析proceed方法了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec, RealConnection connection) throws IOException {
...
// 这里又创建了一次RealInterceptorChain,只是把index+1。
RealInterceptorChain next = new RealInterceptorChain(
interceptors, streamAllocation, httpCodec,
connection, index + 1, request,
call, eventListener, connectTimeout,
readTimeout, writeTimeout);
// 最初情况下,index = 0,
// 所以我们get的就是RetryAndFollowUpInterceptor
Interceptor interceptor = interceptors.get(index);
// 这里我们调用的是RetryAndFollowUpInterceptor.intercept()
Response response = interceptor.intercept(next);
...
return response;
}

现在我们看一下RetryAndFollowUpInterceptor的类的注释,再来分析RetryAndFollowUpInterceptor.intercept()

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* This interceptor recovers from failures and follows redirects as necessary. It may throw an
* {@link IOException} if the call was canceled.
* 这个interceptor会恢复失败并且在必要的时候遵循重定向,这里可能会抛出一个异常如果请求被取消
*/
public final class RetryAndFollowUpInterceptor implements Interceptor {
/**
* 这个Interceptor的intercept实例了很多东西,所以当我们用到的时候我们再去看这个方法。
**/
@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 streamAllocation = new StreamAllocation(
client.connectionPool(), createAddress(request.url()),
call, eventListener, callStackTrace);
this.streamAllocation = streamAllocation;
int followUpCount = 0;
Response priorResponse = null;
while (true) {
// 到我们分析的情况,canceled为false。
if (canceled) {
streamAllocation.release();
throw new IOException("Canceled");
}
Response response;
boolean releaseConnection = true;
try {
// 这里是在调用创建RetryAndFollowUpInterceptor之前创建的Chain
// 这样分析又回到了RealInterceptorChain,其中index = 1.
// 我们通过上面的分析,直接可以得出他调用interceptors.get(1).intercept
response = realChain.proceed(request, streamAllocation, null, null);
releaseConnection = false;
} catch (RouteException e) {
...
} catch (IOException e) {
...
} finally {
...
}
...
}
}
}

所以我们总结一下RetryAndFollowUpInterceptor在proceedz之前做了什么,其实就是创建了StreamAllocation,并执行了一个无线循环,里面执行到我们目前要分析的realChain.proceed(),也就是执行了BridgeInterceptor,所以我们要分析BridgeInterceptor.intercept()

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* Bridges from application code to network code. First it builds a network request from a user
* request. Then it proceeds to call the network. Finally it builds a user response from the network
* response.
* 从应用程序代码到网络代码的桥梁。
* 首先,它根据用户请求构建网络请求。
* 然后它继续呼叫网络。
* 最后,它根据网络响应构建用户响应。
*/
public final class BridgeInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
Request userRequest = chain.request();
Request.Builder requestBuilder = userRequest.newBuilder();
RequestBody body = userRequest.body();
// 我们的请求没有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");
}
}
// 当用户没有设置header的时候,会默认设置下面两个逻辑
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");
}
// 查找这个Request之前是否有cookie,有的话把他加进header里。
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());
}
// 之后开始走CacheInterceptor.intercept
Response networkResponse = chain.proceed(requestBuilder.build());
...
}
}

BridgeInterceptor的主要工作是将Request的header设置好,接下来我们来看CacheInterceptor.intercept()

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
/**
* Serves requests from the cache and writes responses to the cache.
* 提供来自缓存的请求并将响应写入缓存。
**/
public final class CacheInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
// 这个cache是用户在使用OkhttpClient.Builder自己创建的
// 因为要分析整个流程,所以我们就当创建了这个cache。
// 但是我们这算是第一次请求这个url,所以按道理来讲没有缓存。
// 根据上面的分析,cache.get(chain.request()) = null
Response cacheCandidate = cache != null
? cache.get(chain.request())
: null;
long now = System.currentTimeMillis();
// 这里我们就不贴代码了,CacheStrategy(networkRequest, cacheResponse=null)
CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
Request networkRequest = strategy.networkRequest;
Response cacheResponse = strategy.cacheResponse;
...
// 之前的逻辑都不是匹配我们现在这个缓存策略的。
Response networkResponse = null;
try {
// 所以我们之后要分析这个代码了
networkResponse = chain.proceed(networkRequest);
} finally {
...
}
...
}
}

这里我们先看一下cache.get(request.url)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Nullable Response get(Request request) {
// cache依据url来生成key
String key = key(request.url());
DiskLruCache.Snapshot snapshot;
Entry entry;
try {
// 先来看看cache.get,目前的流程snapshot为空,所以直接返回null
snapshot = cache.get(key);
if (snapshot == null) {
return null;
}
} catch (IOException e) {
...
}
...
}

这里来看看cache.get(),感觉从这里的分析,感受到应该要尊重编译的流程,不然我大脑里也不知道某些变量某些列表是用来干嘛的,这样挺可怕的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public final class DiskLruCache implements Closeable, Flushable {
/**
* Returns a snapshot of the entry named {@code key}, or null if it doesn't exist is not currently
* readable. If a value is returned, it is moved to the head of the LRU queue.
*/
public synchronized Snapshot get(String key) throws IOException {
// 这个方法是用来获得一个journalFile的,我直接在这里解释一下这个方法做了什么。
// 我们在创建Cache的时候创建了一个File,这个方法是用来保存JournalFile的
// 这个JournalFile就是用来保存缓存的。
initialize();
checkNotClosed();
validateKey(key);
// 我们这次请求是第一次请求,所以lruEntries没有我们要的缓存。
Entry entry = lruEntries.get(key);
// 因为entry = null 所以直接返回null了
if (entry == null || !entry.readable) return null;
...
}
}

这里我们来分析一下下一个Interceptor,ConnectInterceptor,好吧,ConnectInterceptor目前我还无法理解,他需要一些关于连接池的知识,可能关联到网络层的问题。之后我去别人博客看看关于这方面的东西

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* Opens a connection to the target server and proceeds to the next interceptor.
* 打开与目标服务器的连接,然后继续执行下一个拦截器。
*/
public final class ConnectInterceptor implements Interceptor {
@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);
}
}

接下来来看一下下一个Interceptor,NetworkInterceptor,这里的代码我们先放一放,因为我看的不是太懂,所以我们先去分析下一个Interceptor,

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
33
34
35
final class NetworkInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// Double-check the URL filter to prevent redirects from hitting filtered URLs.
if (urlFilter != null) {
urlFilter.checkURLPermitted(request.url().url());
}
synchronized (lock) {
connectPending = false;
proxy = chain.connection().route().proxy();
handshake = chain.connection().handshake();
lock.notifyAll();
try {
while (!proceed) {
lock.wait(); // Wait until proceed() is called.
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Retain interrupted status.
throw new InterruptedIOException();
}
}
// Try to lock in the Content-Length before transmitting the request body.
if (request.body() instanceof OutputStreamRequestBody) {
OutputStreamRequestBody requestBody = (OutputStreamRequestBody) request.body();
request = requestBody.prepareToSendRequest(request);
}
Response response = chain.proceed(request);
...
}
}

这里是关于CallServerInterceptor的分析,所以到这里,我们的请求已经成功发送,也成功返回,之后我们来就要将response进行处理。所以我们要逆着去再走interceptor了。

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
public final class CallServerInterceptor implements Interceptor {
private final boolean forWebSocket;
@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());
// 这个方法是用来将header通过okio写的
httpCodec.writeRequestHeaders(request);
realChain.eventListener().requestHeadersEnd(realChain.call(), request);
Response.Builder responseBuilder = null;
// 之后这里是用来写body的,因为我们这个请求没有body,所以暂时不去考虑
if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
...
}
// 将请求刷新到底层套接字并发出信号,不再传输字节。
// 至此,我们请求已经成功发送完了.
httpCodec.finishRequest();
if (responseBuilder == null) {
realChain.eventListener().responseHeadersStart(realChain.call());
// 这里就是我们就是接收服务端的response的header了。
responseBuilder = httpCodec.readResponseHeaders(false);
}
// 这个就是我们的response
Response response = responseBuilder
.request(request)
.handshake(streamAllocation.connection().handshake())
.sentRequestAtMillis(sentRequestMillis)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
int code = response.code();
// 判断response的code值,这里直接讲一下关于code的内容
// 1xx: 表示通知信息的,如请求收到了或正在进行处理
// 2xx: 表示成功,如接受或知道了。
// 3xx: 表示重定向,如要完成请求还必须采取进一步的行动
// 4xx: 表示客户端的差错,如请求中有错误的语法或不能完成
// 5xx: 服务器的差错,如服务器失效无法完成请求。
if (code == 100) {
// server sent a 100-continue even though we did not request one.
// try again to read the actual response
responseBuilder = httpCodec.readResponseHeaders(false);
response = responseBuilder
.request(request)
.handshake(streamAllocation.connection().handshake())
.sentRequestAtMillis(sentRequestMillis)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
code = response.code();
}
realChain.eventListener()
.responseHeadersEnd(realChain.call(), response);
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;
}
}

所以我们又回到了NetworkInterceptor,并且执行到chain.proceed(request);,我们再来看之后执行代码。这个NetworkInterceptor之后的工作只是将变量放入全局变量中。

1
2
3
4
5
6
7
8
9
10
11
12
13
final class NetworkInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
...
Response response = chain.proceed(request);
synchronized (lock) {
networkResponse = response;
url = response.request().url().url();
}
return response;
}
}

接下来的ConnectInterceptor并没有做任何之后的操作。所以我们可以直接看上面的CacheInterceptor。

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
33
34
35
36
37
38
39
40
41
42
public final class CacheInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
...
// 执行到这里,networkResponse 不为空,cacheResponse为空。
try {
networkResponse = chain.proceed(networkRequest);
} finally {
if (networkResponse == null && cacheCandidate != null) {
...
}
}
// If we have a cache response too, then we're doing a conditional get.
// 因为cacheResponse为空,所以这里我们先不执行
if (cacheResponse != null) {
...
}
// stripBody就是将Response的body剔除掉。
// 所以这个Response就是一个没有body的response。
Response response = networkResponse.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
// 这个cache是我们在初始化OkhttpClient自己初始化的
// 所以这里的cache不为空。
if (cache != null) {
// 判断response是否有body并且判断这个response是否可以被缓存。
if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
// Offer this request to the cache.
// 这里很有意思,这个缓存的东西只会缓存GET请求。
// 因为我们现在这个方法是GET请求,而且之前GET请求是没有body的
// 所以这里我们这里判断是可以缓存了。
CacheRequest cacheRequest = cache.put(response);
...
}
...
}
...
}
}

这里我们要分析一下cache.put(response);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public final class Cache implements Closeable, Flushable {
@Nullable CacheRequest put(Response response) {
// 前面的代码就是判断这个请求是否可以加入到cache。
// 所以我们直接分析下面的代码
...
Entry entry = new Entry(response);
DiskLruCache.Editor editor = null;
try {
// 这里我们要看一下关于这个edit
editor = cache.edit(key(response.request().url()));
...
} catch (IOException e) {
...
}
}
}

这里我们看一下关于cache.edit(key(response.request().url()));

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
33
34
35
36
/**
* Returns an editor for the entry named {@code key}, or null if another edit is in progress.
* 返回名为{@code key}的条目的编辑器,如果正在进行其他编辑,则返回null。
*/
public @Nullable Editor edit(String key) throws IOException {
// ANY_SEQUENCE_NUMBER = -1;
return edit(key, ANY_SEQUENCE_NUMBER);
}
synchronized Editor edit(String key, long expectedSequenceNumber) throws IOException {
// 这个方法还是用来初始化JournalFile
initialize();
checkNotClosed();
validateKey(key);
// lruEntries是一个LinkedHashMap
Entry entry = lruEntries.get(key);
...
// Flush the journal before creating files to prevent file leaks.
// 在创建文件之前刷新日志以防止文件泄漏。
journalWriter.writeUtf8(DIRTY).writeByte(' ').writeUtf8(key).writeByte('\n');
journalWriter.flush();
...
// 如果entry为空的话,创建一个entry,并放入到lruEntries
if (entry == null) {
entry = new Entry(key);
lruEntries.put(key, entry);
}
// 这里再创建了一个Editor并返回
Editor editor = new Editor(entry);
entry.currentEditor = editor;
return editor;
}

之后我们再返回到cache.put(response);,到了最后Cache返回了CacheRequestImpl。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public final class Cache implements Closeable, Flushable {
@Nullable CacheRequest put(Response response) {
...
try {
editor = cache.edit(key(response.request().url()));
if (editor == null) {
return null;
}
entry.writeTo(editor);
// 这里只是做了一些初始化的操作
return new CacheRequestImpl(editor);
} catch (IOException e) {
...
}
}
}

之后再回到CacheInterceptor.intercept()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public final class CacheInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
if (cache != null) {
if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
// Offer this request to the cache.
CacheRequest cacheRequest = cache.put(response);
// 这里我们返回了一个新的response。
return cacheWritingResponse(cacheRequest, response);
}
if (HttpMethod.invalidatesCache(networkRequest.method())) {
try {
cache.remove(networkRequest);
} catch (IOException ignored) {
// The cache cannot be written.
}
}
}
return response;
}
}

之后我们再看上一层的Interceptor,BridgeInterceptor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public final class BridgeInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
Response networkResponse = chain.proceed(requestBuilder.build());
//
HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
Response.Builder responseBuilder = networkResponse.newBuilder()
.request(userRequest);
// 因为我们的请求里面没有body,所以不用走这个请求。
if (transparentGzip
&& "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))
&& HttpHeaders.hasBody(networkResponse)) {
...
}
// 所以直接返回新建的response
return responseBuilder.build();
}
}

最后再回去看RetryAndFollowUpInterceptor.interceptor

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
public final class RetryAndFollowUpInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
...
while (true) {
...
try {
response = realChain.proceed(request, streamAllocation, null, null);
releaseConnection = false;
} catch (RouteException e) {
...
} catch (IOException e) {
...
} finally {
// We're throwing an unchecked exception. Release any resources.
// releaseConnection = false
if (releaseConnection) {
streamAllocation.streamFailed(null);
streamAllocation.release();
}
}
// Attach the prior response if it exists. Such responses never have a body.
// priorResponse = null
if (priorResponse != null) {
...
}
Request followUp;
try {
// 这个方法就是处理异常情况下的request。
followUp = followUpRequest(response, streamAllocation.route());
} catch (IOException e) {
streamAllocation.release();
throw e;
}
// 正常的请求,到这里就结束了。
if (followUp == null) {
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);
this.streamAllocation = streamAllocation;
} 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;
}
}
}