okhttp 之 ConnectInterceptor拦截器分析

还是一样 先从重写方法开始

  public final OkHttpClient client;

public ConnectInterceptor(OkHttpClient client) {
this.client = client;
  }

@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");
//通过newStream  获取一个   HttpCodec 
HttpCodec httpCodec = streamAllocation.newStream(client, chain, doExtensiveHealthChecks);
//获得一个连接
RealConnection connection = streamAllocation.connection();

return realChain.proceed(request, streamAllocation, httpCodec, connection);
 }

我们先进入.newStream(client, chain, doExtensiveHealthChecks) 这个方法看下

public HttpCodec newStream(
  OkHttpClient client, Interceptor.Chain chain, boolean doExtensiveHealthChecks) {
 //获取连接超时时间
int connectTimeout = chain.connectTimeoutMillis();
//读写等超时时间
int readTimeout = chain.readTimeoutMillis();
int writeTimeout = chain.writeTimeoutMillis();
int pingIntervalMillis = client.pingIntervalMillis();
boolean connectionRetryEnabled = client.retryOnConnectionFailure();

try {
// findHealthyConnection 找一个SOCKET连接  先判断有没有健康的连接 没有则重新握手  创建  连接缓存
  RealConnection resultConnection = findHealthyConnection(connectTimeout, readTimeout,
      writeTimeout, pingIntervalMillis, connectionRetryEnabled, doExtensiveHealthChecks);
   //基于okio的输入输出流  具体可以进去看源码 返回一个 HttpCodec
    HttpCodec resultCodec = resultConnection.newCodec(client, chain, this)
        //拿到一个连接;
     RealConnection connection = streamAllocation.connection();
  synchronized (connectionPool) {
    codec = resultCodec;
    return resultCodec;
  }
} catch (IOException e) {
  throw new RouteException(e);
}

}

我们进入 findHealthyConnection这个方法看下

 private RealConnection findHealthyConnection(int connectTimeout, int readTimeout,
  int writeTimeout, int pingIntervalMillis, boolean connectionRetryEnabled,
  boolean doExtensiveHealthChecks) throws IOException {
while (true) {

  RealConnection candidate = findConnection(connectTimeout, readTimeout, writeTimeout,
      pingIntervalMillis, connectionRetryEnabled);
  //后面没啥看的
  // If this is a brand new connection, we can skip the extensive health checks.
  synchronized (connectionPool) {
    if (candidate.successCount == 0) {
      return candidate;
    }
  }

  // Do a (potentially slow) check to confirm that the pooled connection is still good. If it
  // isn't, take it out of the pool and start again.
  if (!candidate.isHealthy(doExtensiveHealthChecks)) {
    noNewStreams();
    continue;
  }

  return candidate;
}

}
我们再进入 findConnection 这个方法

/**
 * Returns a connection to host a new stream. This prefers the existing connection if it      exists,
  * then the pool, finally building a new connection.
 */
private RealConnection findConnection(int connectTimeout, int readTimeout, int writeTimeout,
  int pingIntervalMillis, boolean connectionRetryEnabled) throws IOException {
boolean foundPooledConnection = false;
RealConnection result = null;
Route selectedRoute = null;
Connection releasedConnection;
Socket toClose;
synchronized (connectionPool) {
  if (released) throw new IllegalStateException("released");
  if (codec != null) throw new IllegalStateException("codec != null");
  if (canceled) throw new IOException("Canceled");

  // Attempt to use an already-allocated connection. We need to be careful here because our
  // already-allocated connection may have been restricted from creating new streams.
  releasedConnection = this.connection;
  toClose = releaseIfNoNewStreams();
  if (this.connection != null) {
    // We had an already-allocated connection and it's good.
    result = this.connection;
    releasedConnection = null;
  }
// 做一系列的判断
  ...  
  synchronized (connectionPool) {
  if (canceled) throw new IOException("Canceled");

  if (newRouteSelection) {
    // Now that we have a set of IP addresses, make another attempt at getting a connection from
    // the pool. This could match due to connection coalescing.
    //循环路由
    List<Route> routes = routeSelection.getAll();
    for (int i = 0, size = routes.size(); i < size; i++) {
      Route route = routes.get(i);
      Internal.instance.get(connectionPool, address, this, route);
      if (connection != null) {
        foundPooledConnection = true;
        result = connection;
        this.route = route;
        break;
      }
    }
  }

  if (!foundPooledConnection) {
    if (selectedRoute == null) {
      selectedRoute = routeSelection.next();
    }

    // Create a connection and assign it to this allocation immediately. This makes it possible
    // for an asynchronous cancel() to interrupt the handshake we're about to do.
    route = selectedRoute;
    refusedStreamCount = 0;
 //如果没有找到可用的 
    result = new RealConnection(connectionPool, selectedRoute);
    acquire(result, false);
  }
}

// If we found a pooled connection on the 2nd time around, we're done.
if (foundPooledConnection) {
  eventListener.connectionAcquired(call, result);
  return result;
}

// Do TCP + TLS handshakes. This is a blocking operation.
//建立连接
result.connect(connectTimeout, readTimeout, writeTimeout, pingIntervalMillis,
    connectionRetryEnabled, call, eventListener);
routeDatabase().connected(result.route());

Socket socket = null;
synchronized (connectionPool) {
  reportedAcquired = true;

  // Pool the connection.
  Internal.instance.put(connectionPool, result);

  // If another multiplexed connection to the same address was created concurrently, then
  // release this connection and acquire that one.
  if (result.isMultiplexed()) {
    socket = Internal.instance.deduplicate(connectionPool, address, this);
    result = connection;
  }
}
closeQuietly(socket);

eventListener.connectionAcquired(call, result);
return result;

}
我们再进入.connect这个方法看下

public void connect(int connectTimeout, int readTimeout, int writeTimeout,
  int pingIntervalMillis, boolean connectionRetryEnabled, Call call,
  EventListener eventListener) {
if (protocol != null) throw new IllegalStateException("already connected");

RouteException routeException = null;
List<ConnectionSpec> connectionSpecs = route.address().connectionSpecs();
ConnectionSpecSelector connectionSpecSelector = new ConnectionSpecSelector(connectionSpecs);

if (route.address().sslSocketFactory() == null) {
  if (!connectionSpecs.contains(ConnectionSpec.CLEARTEXT)) {
    throw new RouteException(new UnknownServiceException(
        "CLEARTEXT communication not enabled for client"));
  }
  String host = route.address().url().host();
  if (!Platform.get().isCleartextTrafficPermitted(host)) {
    throw new RouteException(new UnknownServiceException(
        "CLEARTEXT communication to " + host + " not permitted by network security policy"));
  }
}

while (true) {
  try {
      //HTTPS 隧道
    if (route.requiresTunnel()) {
      connectTunnel(connectTimeout, readTimeout, writeTimeout, call, eventListener);
      if (rawSocket == null) {
        // We were unable to connect the tunnel but properly closed down our resources.
        break;
      }
    } else {
      //进行一个Socket 连接
      connectSocket(connectTimeout, readTimeout, call, eventListener);
    }
    establishProtocol(connectionSpecSelector, pingIntervalMillis, call, eventListener);
    eventListener.connectEnd(call, route.socketAddress(), route.proxy(), protocol);
    break;
  } catch (IOException e) {
    closeQuietly(socket);
    closeQuietly(rawSocket);
    socket = null;
    rawSocket = null;
    source = null;
    sink = null;
    handshake = null;
    protocol = null;
    http2Connection = null;

    eventListener.connectFailed(call, route.socketAddress(), route.proxy(), null, e);

    if (routeException == null) {
      routeException = new RouteException(e);
    } else {
      routeException.addConnectException(e);
    }

    if (!connectionRetryEnabled || !connectionSpecSelector.connectionFailed(e)) {
      throw routeException;
    }
  }
}

if (route.requiresTunnel() && rawSocket == null) {
  ProtocolException exception = new ProtocolException("Too many tunnel connections attempted: "
      + MAX_TUNNEL_ATTEMPTS);
  throw new RouteException(exception);
}

if (http2Connection != null) {
  synchronized (connectionPool) {
    allocationLimit = http2Connection.maxConcurrentStreams();
  }
}

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 因为项目集成,在使用Fresco的时候,有集成OkHttp,所以接下来是OkHttp3.0的 简单一个列子,其中里...
    TragedyGo阅读 5,403评论 0 1
  • 简介 目前在HTTP协议请求库中,OKHttp应当是非常火的,使用也非常的简单。网上有很多文章写了关于OkHttp...
    第八区阅读 5,202评论 1 5
  • 周得到006 20180521-20180527 壹|精读营之旅 精读营历时半个月,前两天的准备,十天的打卡,后三...
    过云雨Milo阅读 1,738评论 0 1
  • 小住老屋(二) 母亲张罗着烧中饭。我帮母亲着火。母亲不让,她怕灶堂的灰沾到我身上。看着母亲把树叶送进灶堂,我问母亲...
    春之原野阅读 3,180评论 5 6
  • CASSIEVONG诗无是英国轻奢珠宝品牌, 致力于打造属于现代女性诗意无限的幻美仙境, 每件珠宝饰品都拥有最新颖...
    CASSIEVONG诗无阅读 3,793评论 0 0

友情链接更多精彩内容