基于OkHttp:3.12.0:https://github.com/square/okhttp/tree/okhttp_3.12.x
Read The Fucking Source Code
OkHttpClient#newCall(new Request())#enquenue(new Callback(){})
OkHttpClient#newCall(new Request())
:OkHttpClient根据client、request创建RealCall,RealCall里面包含所有请求的各种配置信息:拦截器、请求连接、调度器Dispatcher、ConnectionPool等//OkHttpClient
@Override public Call newCall(Request request) {
return RealCall.newRealCall(this, request, false /* for web socket */);
}
RealCall#enqueue(new Callback(){})
:
//RealCall
@Override public void enqueue(Callback responseCallback) {
//其它信息...
client.dispatcher().enqueue(new AsyncCall(responseCallback));
}
// Dispatcher
void enqueue(AsyncCall call) {
synchronized (this) {
readyAsyncCalls.add(call);
}
promoteAndExecute();
}
//Dispatcher
private boolean promoteAndExecute() {
//...
List executableCalls = new ArrayList<>();
//伪代码...
if(满足一定条件){executableCalls.addAll(readyAsyncCalls)}
for (int i = 0, size = executableCalls.size(); i < size; i++) {
AsyncCall asyncCall = executableCalls.get(i);
asyncCall.executeOn(executorService());
}
return isRunning;
}
AsyncCall#executeOn(executorService())
:
//AsyncCall
void executeOn(ExecutorService executorService) {
//...
executorService.execute(this);//这里会调用父类的run方法
//...
}
//NamedRunnable, AsyncCall的父类
public abstract class NamedRunnable implements Runnable {
//...
@Override public final void run() {
//...
execute();
}
//子类AsyncCall做对应实现
protected abstract void execute();
}
#AsyncCall
@Override protected void execute() {
boolean signalledCallback = false;
timeout.enter();
try {
//关键,去获取response对象,真正的耗时也就在这
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) {
e = timeoutExit(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);
}
}
}
RealCall#getResponseWithInterceptorChain
:
chain.proceed(requestBuilder.build())
,注意Chain是上一个创建的RealInterceptorChain,所以又跑到了第二步,同时index这个时候已经+1,如此完成递归操作!#RealCall
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
List 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);
}
#RealInterceptorChain
@Override public Response proceed(Request request) throws IOException {
return proceed(request, streamAllocation, httpCodec, connection);
}
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对应的拦截器
Interceptor interceptor = interceptors.get(index);
//执行取到的拦截器
Response response = interceptor.intercept(next);
//...
return response;
}
# BridgeInterceptor
@Override public Response intercept(Chain chain) throws IOException {
//根据上游chain继续处理当前拦截器。注意:chain的源头:RealInterceptorChain#proceed中创建的next,一个新的RealInterceptorChain
Request userRequest = chain.request();
Request.Builder requestBuilder = userRequest.newBuilder();
//各种逻辑,跳过只看核心...
//核心,这里又回到了RealInterceptorChain#proceed
Response networkResponse = chain.proceed(requestBuilder.build());
//后续逻辑...
return responseBuilder.build();
}