我们先来看看Okhttp的简单实用,我相信这些大家都不会陌生
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().build();
try {
okHttpClient.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
从这里开始我们开始查看源码
public Response execute() throws IOException {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
try {
client.dispatcher().executed(this);
//Okhttp的精华方法所在了,通过递归调用Interceptor,完成出栈
Response result = getResponseWithInterceptorChain(false);
if (result == null) throw new IOException("Canceled");
return result;
} finally {
client.dispatcher().finished(this);
}
}
下面我们继续看getResponseWithInterceptorChain是如何进行递归的
public Response proceed(Request request) throws IOException {
// If there's another interceptor in the chain, call that.
if (index < client.interceptors().size()) {
Interceptor.Chain chain = new ApplicationInterceptorChain(index + 1, request, forWebSocket);
Interceptor interceptor = client.interceptors().get(index);
Response interceptedResponse = interceptor.intercept(chain);
if (interceptedResponse == null) {
throw new NullPointerException("application interceptor " + interceptor
+ " returned null");
}
return interceptedResponse;
}
// No more interceptors. Do HTTP.
return getResponse(request, forWebSocket);
}
}
当全部递归完成之后,来到了getResponse,也就是真正的进行网络操作了