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();
  }
}

}

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 因為項目集成,在使用Fresco的時候,有集成OkHttp,所以接下來是OkHttp3.0的 簡單一個列子,其中里...
    TragedyGo閱讀 1,399評論 0 1
  • 簡介 目前在HTTP協議請求庫中,OKHttp應當是非常火的,使用也非常的簡單。網上有很多文章寫了關于OkHttp...
    第八區閱讀 1,397評論 1 5
  • 周得到006 20180521-20180527 壹|精讀營之旅 精讀營歷時半個月,前兩天的準備,十天的打卡,后三...
    過云雨Milo閱讀 246評論 0 1
  • 小住老屋(二) 母親張羅著燒中飯。我幫母親著火。母親不讓,她怕灶堂的灰沾到我身上。看著母親把樹葉送進灶堂,我問母親...
    春之原野閱讀 442評論 5 6
  • CASSIEVONG詩無是英國輕奢珠寶品牌, 致力于打造屬于現代女性詩意無限的幻美仙境, 每件珠寶飾品都擁有最新穎...
    CASSIEVONG詩無閱讀 639評論 0 0