我們先來看看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);
}
}
下面我們繼續(xù)看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,也就是真正的進行網絡操作了