目录
系列文章:
OKHttp开源框架学习三:任务调度核心类Dispatcher
OKHttp开源框架学习五:拦截器之RetryAndFollowUpInterceptor
OKHttp开源框架学习六:拦截器之BridgeInterceptor
OKHttp开源框架学习八:拦截器之CacheInterceptor
OKHttp开源框架学习九:拦截器之ConnectInterceptor
OKHttp开源框架学习十:ConnectionPool连接池
OKHttp开源框架学习十一:拦截器之CallServerInterceptor
代码:
@Override
public Response intercept(Chain chain) throws IOException {
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Request request = realChain.request();
StreamAllocation streamAllocation = realChain.streamAllocation();
// We need the network to satisfy this request. Possibly for validating a conditional GET.
boolean doExtensiveHealthChecks = !request.method().equals("GET");
HttpCodec httpCodec = streamAllocation.newStream(client, chain, doExtensiveHealthChecks);
RealConnection connection = streamAllocation.connection();
return realChain.proceed(request, streamAllocation, httpCodec, connection);
}
总结:
1、ConnectInterceptor获取Interceptor传过来的StreamAllocation,streamAllocation.newStream()
2、将刚才创建的用于网络IO的RealConnection对象,以及对于与服务器交互最为关键的HttpCodec等对象传递给后面的拦截器
我们来看newStream()方法:
public HttpCodec newStream(
OkHttpClient client, Interceptor.Chain chain, boolean doExtensiveHealthChecks) {
int connectTimeout = chain.connectTimeoutMillis();
int readTimeout = chain.readTimeoutMillis();
int writeTimeout = chain.writeTimeoutMillis();
boolean connectionRetryEnabled = client.retryOnConnectionFailure();
try {
RealConnection resultConnection = findHealthyConnection(connectTimeout, readTimeout,
writeTimeout, connectionRetryEnabled, doExtensiveHealthChecks);
HttpCodec resultCodec = resultConnection.newCodec(client, chain, this);
synchronized (connectionPool) {
codec = resultCodec;
return resultCodec;
}
} catch (IOException e) {
throw new RouteException(e);
}
}
总结2:
1、创建一个RealConnection对象
2、选择不同的连接方式:一种是socket连接,另一种是tunnel隧道连接
3、调用CallServerInterceptor