上一节讲到了OkHttpClient里面的属性。这节就讲到newCall说返回对象的类型Call.
这次我们还是顺着OkHttpClinet的使用作为线索来读。
一个典型的同步方法是
new OkhttpClient().newCall(request).excute();
我们重点来看Call里的execute()使用方法。
public Response execute()
throws IOException
{
synchronized (this)
{
if (this.executed) {
throw new IllegalStateException("Already Executed");
}
this.executed = true;
}
try
{
this.client.getDispatcher().executed(this);
Response result = getResponseWithInterceptorChain(false);
if (result == null) {
throw new IOException("Canceled");
}
return result;
}
finally
{
this.client.getDispatcher().finished(this);
}
}
通过DistPatcher(第一节中OkHttpClient的分发器),在getResponseWithInterceptorChain(boolean)前后分别调用executed() finished()方法。
而这段代码的重点是getResponseWithInterceptorChain(boolean)这个方法。
private Response getResponseWithInterceptorChain(boolean forWebSocket)
throws IOException
{
Interceptor.Chain chain = new ApplicationInterceptorChain(0, this.originalRequest, forWebSocket);
return chain.proceed(this.originalRequest);
}
然后我们按图索骥,去研究Interceptor.Chain,它的实现还是在Call这个类型中
class ApplicationInterceptorChain
implements Interceptor.Chain
{
private final int index;
private final Request request;
private final boolean forWebSocket;
ApplicationInterceptorChain(int index, Request request, boolean forWebSocket)
{
this.index = index;
this.request = request;
this.forWebSocket = forWebSocket;
}
public Connection connection()
{
return null;
}
public Request request()
{
return this.request;
}
public Response proceed(Request request)
throws IOException
{
if (this.index < Call.this.client.interceptors().size())
{
Interceptor.Chain chain = new ApplicationInterceptorChain(Call.this, this.index + 1, request, this.forWebSocket);
Interceptor interceptor = (Interceptor)Call.this.client.interceptors().get(this.index);
Response interceptedResponse = interceptor.intercept(chain);
if (interceptedResponse == null) {
throw new NullPointerException("application interceptor " + interceptor + " returned null");
}
return interceptedResponse;
}
return Call.this.getResponse(request, this.forWebSocket);
}
}
最终是通过Interceptor对象的intercept(chain)方法,获得 interceptedResponse。而interceptor是通过来自client里的interceptor对象。