transmitter.callStart();
try {
1: client.dispatcher().executed(this);
2: return getResponseWithInterceptorChain();
} finally {
结束之后将请求移除出队列
client.dispatcher().finished(this);
}
}
接下来看1出的dispatcher的方法
/** Used by {@code Call#execute} to signal it is in-flight. */
synchronized void executed(RealCall call) {
runningSyncCalls.add(call);
}
public final class Dispatcher {
private int maxRequests = 64;
private int maxRequestsPerHost = 5;
private @Nullable Runnable idleCallback;
/** Executes calls. Created lazily. */
private @Nullable ExecutorService executorService;
/** Ready async calls in the order they’ll be run. /
异步请求队列
private final Deque readyAsyncCalls = new ArrayDeque<>();
正在运行的异步请求队列
/* Running asynchronous calls. Includes canceled calls that haven’t finished yet. /
private final Deque runningAsyncCalls = new ArrayDeque<>();
同步请求队列
/* Running synchronous calls. Includes canceled calls that haven’t finished yet. */
private final Deque runningSyncCalls = new ArrayDeque<>();
public Dispatcher(ExecutorService executorService) {
this.executorService = executorService;
}
publi
c Dispatcher() {
}
}
此处dispatcher就是存储和移除每个请求的地方,每次执行execute或者enqueue的时候dispatcher的功能都只是将请求添加到队列中,重点是上处的2 getResponseWithInterceptorChain 这个方法才是真正运行请求的地方
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
List interceptors = new ArrayList<>();
interceptors.addAll(client.interceptors());,自定义的intercepters
interceptors.add(new RetryAndFollowUpInterceptor(client));
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, transmitter, null, 0,
originalRequest, this, client.connectTimeoutMillis(),
client.readTimeoutMillis(), client.writeTimeoutMillis());
boolean calledNoMoreExchanges = false;
try {
Response response = chain.proceed(originalRequest);
if (transmitter.isCanceled()) {
closeQuietly(response);
throw new IOException(“Canceled”);
}
return response;
} catch (IOException e) {
calledNoMoreExchanges = true;
throw transmitter.noMoreExchanges(e);
} finally {
if (!calledNoMoreExchanges) {
transmitter.noMoreExchanges(null);
}
}
}
上处第一步加入了用户自定义的拦截器,之后加入了系统自定义的五个拦截器
RetryAndFollowUpInterceptor 重试拦截器
BridgeInterceptor 此处会把网络数据封装成http的格式,请求到服务器,并解析返回的http格式的数据
CacheInterceptor 缓存拦截器,处理用户自定义的缓存策略
ConnectInterceptor 连接服务器的拦截器,连接服务器用到socket协议,
networkInterceptors 网络日志拦截器
CallServerInterceptor 此处是socket真正建立连接的地方。
器的拦截器,连接服务器用到socket协议,
networkInterceptors 网络日志拦截器
CallServerInterceptor 此处是socket真正建立连接的地方。