开局一张图剩下全靠编
- 1绿色部分表示共有流程
- 2红色部分表示异步请求
- 蓝色部分表示同步请求
- 上面的图包含了Dispatcher的调度和流程分析
- 由上图可以看到最终都是移除掉RunningAsyncCalls中执行过的Call
- 具体的Diapatcher 线程调度可参考该文章Diapatcher如何调度任务
由上图可知无论同步还是异步最终都是通过getRespinseWithIntercepotrChain() 来获取到Response
在这里用到了责任链模式 此处只分析责任链,以及浅显getRespinseWithIntercepotrChain的过程,该方法内的每一个拦截器职责以及流程请参看
那我们看看这里做了什么操作
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)); // 加入连接拦截器
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.readTimeoutMillis());
// 利用 chain 来链式调用拦截器,最后的返回结果就是 Response 对象
return chain.proceed(originalRequest);
}
}
总结
- 整合了这些拦截器
- 通过
RealInterceptorChain
拦截器链的proceed
方法执行拦截器链 来获取Response 此处利用了责任链模式
好那我们看下proceed方法里做了什么
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException {
if (index >= interceptors.size()) throw new AssertionError();
....
calls++;
// Call the next interceptor in the chain.调用下一个拦截器
// 得到下一次对应的 RealInterceptorChain
RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
connection, index + 1, request, call, eventListener, readTimeout);
// 当前次数的 interceptor
Interceptor interceptor = interceptors.get(index);
// 进行拦截处理,并且在 interceptor 链式调用 next 的 proceed 方法
Response response = interceptor.intercept(next);
// 确认下一次的 interceptor 调用过 chain.proceed()
if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) {
throw new IllegalStateException("network interceptor " + interceptor
+ " must call proceed() exactly once");
}
///.....
return response;
}
}
总结
- 1、proceed中又创建了一个index+1 的拦截器链(next)
- 2、通过当前index拦截器链调用 intercept(next) 传入next 拦截器链
看Intercept方法内部
public Response intercept(Chain chain) throws IOException {
···
try {
//2 调用proceed方法 方法内又创建一个RealInterceptorChain(index+1) 调用 intercep方法
//执行下一个拦截器链
response = realChain.proceed(request, streamAllocation, null, null);
releaseConnection = false;
}
···
}
总结
1、intercept方法内部又调用了proceed方法 执行下一个拦截器
2、proceed方法内又创建了一个(index+1)的拦截器链next,
3、当前index的拦截器链又会执行intercept(next)传入下一个拦截器next,
4、intercept方法内部又调用了proceed方法执行下一个拦截器 构成了一个递归的调用。。一直到最后一个拦截器 看下图
5、这就是okhttp责任链的链式调用过程
重点
- 具体的Diapatcher 线程调度可参考该文章
- getResponseWithInterceptorChain 内部拦截器的具体分析请看下面文章
java代码
package mny.com.mokhttp;
import java.io.IOException;
import java.util.logging.Logger;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Crate by E470PD on 2019/3/18
*/
public class OkHttpTest {
public static void main(String[] args) {
final OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();
final Request request = new Request.Builder()
.url("http://api.github.com/users/flyou")
.build();
Response response = null;
try {
//同步方法
response = client.newCall(request).execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
//异步请求
Call call=client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
}
}
class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Logger.getAnonymousLogger().info(String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
Logger.getAnonymousLogger().info(String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
}