相关文章推荐
潇洒的紫菜汤  ·  Java ...·  7 月前    · 
睿智的领结  ·  华为开发者论坛·  1 年前    · 
绅士的大白菜  ·  18 个 Java8 ...·  1 年前    · 
干练的小刀  ·  向concurrent.futures.Ex ...·  1 年前    · 

一次http请求对应一个call对象,既是RealCall对象。

Transmitter

Transmitter是okhttp中应用层和网络层的桥梁 ,管理同一个Cal的所有连接、请求、响应和IO流之间的关系,它在RealCall创建后就被创建了。

在Transmitter中okhttpclient和call我们都认识,剩下的RealConnectionPool、RealConnection、ExchangeFinder、Exchange都和okhttp的 连接机制 有关,都会在ConnectInterceptor中介绍,Transmitter就是负责管理它们之间的关系。

Exchange

Exchange负责从创建的连接的IO流中写入请求和读取响应,完成一次请求/响应的过程,在CallServerInterceptor中你会看到它真正的作用

ExchangeFinder

ExchangeFinder对象在RetryAndFollowUpInterceptor中通过Transmitter的prepareToConnect方法创建, 它的find方法是连接真正创建的地方.

ExchangeFinder就是 负责连接的创建,把创建好的连接放入连接池,如果连接池中已经有该连接,就直接取出复用 .

ExchangeFinder管理着两个重要的角色:RealConnection、RealConnectionPool。

RealConnection

连接的真正实现,实现了Connection接口,内部利用Socket建立连接

RealConnectionPool

连接池,用来管理连接对象RealConnection

RealConnectionPool 在内部维护了一个线程池,用来执行清理连接任务cleanupRunnable,还维护了一个双端队列connections,用来缓存已经创建的连接。

创建一次连接要经历TCP握手,如果是HTTPS还要经历TLS握手,握手的过程都是耗时的,所以为了提高效率,就需要connections来对连接进行缓存,从而可以复用;还有如果连接使用完毕,长时间不释放,也会造成资源的浪费,所以就需要cleanupRunnable定时清理无用的连接。

okhttp支持5个并发连接,默认每个连接keepAlive为5分钟,keepAlive就是连接空闲后,保持存活的时间。

2.常见的拦截链有

RetryAndFollowUpInterceptor

重试与重定向拦截器

主要做的事情:

1.创建ExchangeFinder,为在ConnectInterceptor中连接的建立做了一个准备。

2.实现重试和重定向功能,内部通过while(true)死循环来进行重试获取Response(有重试上限,超过20次会抛出异常)。

3.其中followUpRequest方法根据响应码来判断属于哪种行为触发的重试和重定向(比如未授权,超时,重定向等),然后构建响应的Request进行下一次请求。如果没有触发重新请求就会直接返回Response。

BridgeInterceptor

桥接拦截器,用于完善请求头

主要做的事情:

1.发送请求前,BridgeInterceptor补全一些http header。

这主要包括Content-Type、Content-Length、Transfer-Encoding、Host、Connection、Accept-Encoding、User-Agent,还加载Cookie,随后创建新的Request,并交给后续的Interceptor处理,以获取响应。

2.收到响应后

保存Cookie

如果服务器返回的响应的content是以gzip压缩过的,则会先进行解压缩,移除响应中的header Content-Encoding和Content-Length,构造新的响应并返回;否则直接返回响应。

CacheInterceptor

缓存拦截器,处理HTTP缓存。

Cache这里的缓存都是基于Map,key是请求中url(debug的时候是: http://localhost:8080/okhttp?msg=123 )的md5,value是在文件中查询到的缓存,页面置换基于LRU算法

主要做的事情:

1.根据Request中获取缓存的Response,然后根据用于设置的缓存策略来进一步判断缓存的Response是否可用以及是否发送网络请求

(CacheControl.FORCE_CACHE因为不会发送网络请求,所以networkRequest一定为空)。

2.如果从网络中读取,此时再次根据缓存策略来决定是否缓存响应。

OkHttp已经有实现Cache的整套策略,在Cache类,但默认情况下不会使用,需要自己在创建OkHttpClient时,手动创建并传给OkHttpClient.Builder。

cache使用方式

        int cacheSize = 10 * 1024 * 1024; // 10 MiB
        File cacheFile =  new File("E:\\okhttpcache");
        Cache cache = new Cache(cacheFile, cacheSize);
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .cache(cache);

ConnectInterceptor

连接拦截器,打开一个连接到远程服务器。

主要做的事情:

1.transmitter.newExchange方法创建Exchange

2.借助前面创建的ExchangeFinder,调用它的find方法,从连接池里面选出链接,如果没有则创建新连接。

3.打开一个连接到远程服务器

4.RealConnection.newCodec(),创建并返回Http1ExchangeCodec(http中所有流对象操作都封装到了Http1ExchangeCodec 实现类中 )

CallServerInterceptor

调用服务拦截器,处理IO,与服务器进行数据交换。是拦截链中的最后一个拦截器。

通过 Http1ExchangeCodec 依次次进行写请求头、请求体(可选)、读响应头、读响应体。

如果请求的header或服务器响应的header中,Connection值为close,CallServerInterceptor还会关闭连接。

3.拦截器使用方式

okhttp拦截器用法很简单,构建OkHttpClient时候通过.addInterceptor()就可以将拦截器加入。

OkHttpClient client = new OkHttpClient.Builder()
     .addInterceptor(new LoggingInterceptor())  //注册应用拦截器
     .addNetworkInterceptor(new LoggingInterceptor()) //注册网络拦截器
     .build();

应用拦截器

1.不需要担心中间响应,如重定向和重试。

2.总是调用一次,即使从缓存提供HTTP响应。

3.遵守应用程序的原始意图。不注意OkHttp注入的头像If-None-Match。

4.允许短路和不通话Chain.proceed()。

5.允许重试并进行多次呼叫Chain.proceed()。

网络拦截器

1.能够对重定向和重试等中间响应进行操作。

2.不调用缓存的响应来短路网络。

3.观察数据,就像通过网络传输一样。

4.访问Connection该请求。

二、每个拦截器源码

入口在RealCall.getResponseWithInterceptorChain

1.RealCall.getResponseWithInterceptorChain

Response getResponseWithInterceptorChain() throws IOException {
     //构建拦截器链,加入拦截器
    // Build a full stack of interceptors.
    List<Interceptor> interceptors = new ArrayList<>();
    //先加入用户自定义拦截器
    interceptors.addAll(client.interceptors());
    //再加入程序必备的拦截器
    // 重试拦截器,网络错误、请求失败等
    interceptors.add(new RetryAndFollowUpInterceptor(client));
    // 桥接拦截器,主要是重构请求头即header
    interceptors.add(new BridgeInterceptor(client.cookieJar()));
    // 缓存拦截器
    interceptors.add(new CacheInterceptor(client.internalCache()));
    // 连接拦截器,连接服务器,https包装
    interceptors.add(new ConnectInterceptor(client));
    // 网络拦截器,websockt不支持,同样是自定义
    if (!forWebSocket) {
      interceptors.addAll(client.networkInterceptors());
     // 服务拦截器,主要是发送(write、input)、读取(read、output)数据
    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);

 做了几件事

1.构建拦截器链,加入拦截器。(内部采用责任链模式)

2.按顺序执行拦截器链上每个拦截器,并最终执行真正的http请求得到返回结果

 2.RealInterceptorChain.proceed

  @Override public Response proceed(Request request) throws IOException {
    return proceed(request, transmitter, exchange);
public Response proceed(Request request, Transmitter transmitter, @Nullable Exchange exchange)
      throws IOException {
    if (index >= interceptors.size()) throw new AssertionError();
    calls++;
    // If we already have a stream, confirm that the incoming request will use it.
    if (this.exchange != null && !this.exchange.connection().supportsUrl(request.url())) {
      throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
          + " must retain the same host and port");
    // If we already have a stream, confirm that this is the only call to chain.proceed().
    if (this.exchange != null && calls > 1) {
      throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
          + " must call proceed() exactly once");
    // Call the next interceptor in the chain.
    RealInterceptorChain next = new RealInterceptorChain(interceptors, transmitter, exchange,
        index + 1, request, call, connectTimeout, readTimeout, writeTimeout);
    Interceptor interceptor = interceptors.get(index);
    Response response = interceptor.intercept(next);
    // Confirm that the next interceptor made its required call to chain.proceed().
    if (exchange != null && index + 1 < interceptors.size() && next.calls != 1) {
      throw new IllegalStateException("network interceptor " + interceptor
          + " must call proceed() exactly once");
    // Confirm that the intercepted response isn't null.
    if (response == null) {
      throw new NullPointerException("interceptor " + interceptor + " returned null");
    if (response.body() == null) {
      throw new IllegalStateException(
          "interceptor " + interceptor + " returned a response with no body");
    return response;

做了几件事

1.对状态及获取的reponse做检查

2.最主要的事情即是构造新的RealInterceptorChain对象,获取对应Interceptor,并调用Interceptor的intercept(next)了

在这里,index充当迭代器或指示器的角色,用于指出当前正在处理的Interceptor。

调用拦截链中第一个拦截器RetryAndFollowUpInterceptor

3.RetryAndFollowUpInterceptor

@Override public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Transmitter transmitter = realChain.transmitter();
    int followUpCount = 0;
    Response priorResponse = null;
//一个while(true)中进行下一个拦截器的调用(即使进行后面的Http请求),如果出现RouteException和IOException异常则重试
//有4中情况会停止重试:The application layer has forbidden retries、We can't send the request body again、This exception is fatal、No more routes to attempt
//如果发生以上4中情况之一则抛出异常,结束while循环,释放资源,该拦截器后面的方法不会再执行了,不会再重试了。往外抛异常
    while (true) {
      transmitter.prepareToConnect(request);
      if (transmitter.isCanceled()) {
        throw new IOException("Canceled");
      Response response;
      boolean success = false;
      try {
        //调用第二个拦截器BridgeInterceptor
        response = realChain.proceed(request, transmitter, null);
        success = true;
      } catch (RouteException e) {
        // The attempt to connect via a route failed. The request will not have been sent.
        if (!recover(e.getLastConnectException(), transmitter, false, request)) {
          throw e.getFirstConnectException();
        continue;
      } catch (IOException e) {
        // An attempt to communicate with a server failed. The request may have been sent.
        boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
        //这个recover方法里面就是在判断是否继续重试,还是抛出异常结束这个拦截器
        if (!recover(e, transmitter, requestSendStarted, request)) throw e;
        continue;
      } finally {
        // The network call threw an exception. Release any resources.
        if (!success) {
          transmitter.exchangeDoneDueToException();
      // Attach the prior response if it exists. Such responses never have a body.
      if (priorResponse != null) {
        response = response.newBuilder()
            .priorResponse(priorResponse.newBuilder()
                    .body(null)
                    .build())
            .build();
      Exchange exchange = Internal.instance.exchange(response);
      Route route = exchange != null ? exchange.connection().route() : null;
      //根据响应码来判断属于哪种行为触发的重试和重定向(比如未授权,超时,重定向等),然后构建响应的Request进行下一次请求。
      Request followUp = followUpRequest(response, route);
      //如果没有触发重新请求就会直接返回Response。
      if (followUp == null) {
        if (exchange != null && exchange.isDuplex()) {
          transmitter.timeoutEarlyExit();
        return response;
      RequestBody followUpBody = followUp.body();
      if (followUpBody != null && followUpBody.isOneShot()) {
        return response;
      closeQuietly(response.body());
      if (transmitter.hasExchange()) {
        exchange.detachWithViolence();
      //最大重试次数为20
      if (++followUpCount > MAX_FOLLOW_UPS) {
        throw new ProtocolException("Too many follow-up requests: " + followUpCount);
      request = followUp;
      priorResponse = response;

做了几件事

重试与重定向拦截器

主要做的事情:

1.while(true),出错重试

2.transmitter.prepareToConnect(request)方法准备创建一个连接。 如果存在连接,则优先使用现有连接。

创建ExchangeFinder,为在ConnectInterceptor中连接的建立做了一个准备。

3.realChain.proceed方法

进行下一个拦截器的调用(即是进行后面的Http请求)

4.如果该次HTTP请求出现重大异常则结束重试,抛出异常,释放资源(transmitter.exchangeDoneDueToException();)

如果出现RouteException和IOException异常则重试调用recover方法判断再情况下是否还需要重试

有4中情况会停止重试:

The application layer has forbidden retries、这是判断okhttpclient的retryOnConnectionFailure属性值

We can't send the request body again、这是判断requestSendStarted属性值和异常是否为FileNotFoundException

This exception is fatal、这是判断异常是否为ProtocolException、SocketTimeoutException、CertificateException、SSLPeerUnverifiedException

No more routes to attempt、这是判断exchangeFinder.hasStreamFailure() && exchangeFinder.hasRouteToTry();

5.followUpRequest方法

根据响应码responseCode来判断属于哪种行为触发的重试和重定向(比如未授权,超时,重定向等),然后构建请求的Request进行下一次请求。如果没有触发重新请求就会直接返回Response。

以下responseCode可能会导致重试:

HTTP_PROXY_AUTH = 407

HTTP_UNAUTHORIZED = 401

HTTP_PERM_REDIRECT = 308

HTTP_TEMP_REDIRECT = 307

HTTP_MULT_CHOICE = 300

HTTP_MOVED_PERM = 301

HTTP_MOVED_TEMP = 302

HTTP_SEE_OTHER = 303

HTTP_CLIENT_TIMEOUT = 408

HTTP_UNAVAILABLE = 503

6.closeQuietly(response.body())方法

7.最大重试次数MAX_FOLLOW_UPS为20

4.BridgeInterceptor

 @Override public Response intercept(Chain chain) throws IOException {
    Request userRequest = chain.request();
    Request.Builder requestBuilder = userRequest.newBuilder();
    RequestBody body = userRequest.body();
    //在调用下一个拦截器之前:填充请求头
    if (body != null) {
      MediaType contentType = body.contentType();
      if (contentType != null) {
        requestBuilder.header("Content-Type", contentType.toString());
      long contentLength = body.contentLength();
      if (contentLength != -1) {
        requestBuilder.header("Content-Length", Long.toString(contentLength));
        requestBuilder.removeHeader("Transfer-Encoding");
      } else {
        requestBuilder.header("Transfer-Encoding", "chunked");
        requestBuilder.removeHeader("Content-Length");
    if (userRequest.header("Host") == null) {
      requestBuilder.header("Host", hostHeader(userRequest.url(), false));
    if (userRequest.header("Connection") == null) {
      requestBuilder.header("Connection", "Keep-Alive");
    // If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing
    // the transfer stream.
    boolean transparentGzip = false;
    if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
      transparentGzip = true;
      requestBuilder.header("Accept-Encoding", "gzip");
    List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
    if (!cookies.isEmpty()) {
      requestBuilder.header("Cookie", cookieHeader(cookies));
    if (userRequest.header("User-Agent") == null) {
      requestBuilder.header("User-Agent", Version.userAgent());
    //调用第三个拦截器CacheInterceptor
    Response networkResponse = chain.proceed(requestBuilder.build());
    //解析返回的response中的cookie并保存
    HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
    //将网络请求回来的响应Respond转化为用户可用的response(包括gzip解压)
    Response.Builder responseBuilder = networkResponse.newBuilder()
        .request(userRequest);
    if (transparentGzip
        && "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))
        && HttpHeaders.hasBody(networkResponse)) {
      GzipSource responseBody = new GzipSource(networkResponse.body().source());
      Headers strippedHeaders = networkResponse.headers().newBuilder()
          .removeAll("Content-Encoding")
          .removeAll("Content-Length")
          .build();
      responseBuilder.headers(strippedHeaders);
      String contentType = networkResponse.header("Content-Type");
      responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
    return responseBuilder.build();

做了几件事:

1.在调用下一个拦截器之前:填充请求头

此处可能会填充的请求头有:Content-Type、Content-Length、Transfer-Encoding、Host、Connection、Accept-Encoding、Cookie、User-Agent

2.在下一个拦截器返回response后

HttpHeaders.receiveHeaders解析返回的response中的cookie并保存

将网络请求回来的响应Respond转化为用户可用的response(包括gzip解压)

5.CacheInterceptor

 @Override public Response intercept(Chain chain) throws IOException {
    //1.cache不为空从中获取cacheCandidate
    Response cacheCandidate = cache != null
        ? cache.get(chain.request())
        : null;
    long now = System.currentTimeMillis();
    //2.通过FacheStrategy.Factory获取到缓存策略,获取网络请求与响应缓存
    CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
    Request networkRequest = strategy.networkRequest;
    Response cacheResponse = strategy.cacheResponse;
    if (cache != null) {
      //3.这个方法里面主要是增加缓存命中的计数
      cache.trackResponse(strategy);
    if (cacheCandidate != null && cacheResponse == null) {
      closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
    //4.没网和没缓存的请求下直接返回一个504错误响应
    // If we're forbidden from using the network and the cache is insufficient, fail.
    if (networkRequest == null && cacheResponse == null) {
      return new Response.Builder()
          .request(chain.request())
          .protocol(Protocol.HTTP_1_1)
          .code(504)
          .message("Unsatisfiable Request (only-if-cached)")
          .body(Util.EMPTY_RESPONSE)
          .sentRequestAtMillis(-1L)
          .receivedResponseAtMillis(System.currentTimeMillis())
          .build();
    //5.没网的情况下直接通过响应缓存创建Response并返回
    // If we don't need the network, we're done.
    if (networkRequest == null) {
      return cacheResponse.newBuilder()
          .cacheResponse(stripBody(cacheResponse))
          .build();
    Response networkResponse = null;
    try {
      //6.调用第四个拦截器ConnectInterceptor
      networkResponse = chain.proceed(networkRequest);
    } finally {
      // If we're crashing on I/O or otherwise, don't leak the cache body.
      if (networkResponse == null && cacheCandidate != null) {
        closeQuietly(cacheCandidate.body());
    //7.有响应缓存(cacheResponse != null)并且响应码为304时(networkResponse.code() == HTTP_NOT_MODIFIED)--该响应码意思直接使用缓存。通过cacheResponse创建Response并返回。
    // If we have a cache response too, then we're doing a conditional get.
    if (cacheResponse != null) {
      if (networkResponse.code() == HTTP_NOT_MODIFIED) {
        Response response = cacheResponse.newBuilder()
            .headers(combine(cacheResponse.headers(), networkResponse.headers()))
            .sentRequestAtMillis(networkResponse.sentRequestAtMillis())
            .receivedResponseAtMillis(networkResponse.receivedResponseAtMillis())
            .cacheResponse(stripBody(cacheResponse))
            .networkResponse(stripBody(networkResponse))
            .build();
        networkResponse.body().close();
        // Update the cache after combining headers but before stripping the
        // Content-Encoding header (as performed by initContentStream()).
        cache.trackConditionalCacheHit();
        cache.update(cacheResponse, response);
        return response;
      } else {
        closeQuietly(cacheResponse.body());
    Response response = networkResponse.newBuilder()
        .cacheResponse(stripBody(cacheResponse))
        .networkResponse(stripBody(networkResponse))
        .build();
    //8.cache不为空,有请求头和缓存策略时,通过cache的put方法进行缓存。
    if (cache != null) {
      if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
        // Offer this request to the cache.
        CacheRequest cacheRequest = cache.put(response);
        return cacheWritingResponse(cacheRequest, response);
      if (HttpMethod.invalidatesCache(networkRequest.method())) {
        try {
          cache.remove(networkRequest);
        } catch (IOException ignored) {
          // The cache cannot be written.
    return response;

 做了几件事

1.cache不为空从中获取cacheCandidate

2.通过FacheStrategy.Factory获取到缓存策略,获取网络请求与响应缓存

3.调用cache的同步方法trackResponse,保证请求一致性。

这个方法里面主要是增加缓存命中的计数

4.没网和没缓存的请求下直接返回一个504错误响应

5.没网的情况下直接通过响应缓存创建Response并返回

6.调用下一个拦截链

7.有响应缓存(cacheResponse != null)并且响应码为304时(networkResponse.code() == HTTP_NOT_MODIFIED)--该响应码意思直接使用缓存。通过cacheResponse创建Response并返回。

8.cache不为空,有请求头和缓存策略时,通过cache的put方法将http请求返回的response缓存。

6.ConnectInterceptor

  @Override public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Request request = realChain.request();
    Transmitter transmitter = realChain.transmitter();
    // We need the network to satisfy this request. Possibly for validating a conditional GET.
    boolean doExtensiveHealthChecks = !request.method().equals("GET");
    Exchange exchange = transmitter.newExchange(chain, doExtensiveHealthChecks);
    //调用第五个拦截器CallServerInterceptor
    return realChain.proceed(request, transmitter, exchange);

做了几件事:

1.transmitter.newExchange方法创建Exchange

Exchange负责从创建的连接的IO流中写入请求和读取响应,完成一次请求/响应的过程,在CallServerInterceptor中你会看到它真正的作用

transmitter.newExchange

/** Returns a new exchange to carry a new request and response. */
  Exchange newExchange(Interceptor.Chain chain, boolean doExtensiveHealthChecks) {
    synchronized (connectionPool) {
      if (noMoreExchanges) {
        throw new IllegalStateException("released");
      if (exchange != null) {
        throw new IllegalStateException("cannot make a new request because the previous response "
            + "is still open: please call response.close()");
    ExchangeCodec codec = exchangeFinder.find(client, chain, doExtensiveHealthChecks);
    Exchange result = new Exchange(this, call, eventListener, exchangeFinder, codec);
    synchronized (connectionPool) {
      this.exchange = result;
      this.exchangeRequestDone = false;
      this.exchangeResponseDone = false;
      return result;

做了几件事:

1.通过exchangeFinder.find方法得到exchangeCodec

2.创建Exchange对象

exchangeFinder.find是创建连接的入口

ExchangeFinder对象早在RetryAndFollowUpInterceptor中通过Transmitter的prepareToConnect方法创建,它的find方法是连接真正创建的地方.

ExchangeFinder就是负责连接的创建,把创建好的连接放入连接池,如果连接池中已经有该连接,就直接取出复用.

ExchangeFinder管理着两个重要的角色:RealConnection、RealConnectionPool。

做了几件事 

1.findHealthyConnection()从连接池ConnectionPool获得可用连接RealConnection,且打开了连接

2.resultConnection.newCodec(),创建并返回Http1ExchangeCodec(http中所有流对象操作都封装到了Http1ExchangeCodec实现类中)

这个源码分析看本文后半部分 

7.CallServerInterceptor

@Override public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Exchange exchange = realChain.exchange();
    Request request = realChain.request();
    long sentRequestMillis = System.currentTimeMillis();
    //调用Http1ExchangeCodec的writeRequestHeaders方法写入请求的头部信息
    exchange.writeRequestHeaders(request);
    boolean responseHeadersStarted = false;
    Response.Builder responseBuilder = null;
    //如果不是HEAD不是GET方法,且有请求体,则写入请求体
    if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
      // If there's a "Expect: 100-continue" header on the request, wait for a "HTTP/1.1 100
      // Continue" response before transmitting the request body. If we don't get that, return
      // what we did get (such as a 4xx response) without ever transmitting the request body.
      if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
        exchange.flushRequest();
        responseHeadersStarted = true;
        exchange.responseHeadersStart();
        responseBuilder = exchange.readResponseHeaders(true);
      if (responseBuilder == null) {
        if (request.body().isDuplex()) {
          // Prepare a duplex body so that the application can send a request body later.
          exchange.flushRequest();
          BufferedSink bufferedRequestBody = Okio.buffer(
              exchange.createRequestBody(request, true));
          request.body().writeTo(bufferedRequestBody);
        } else {
          // Write the request body if the "Expect: 100-continue" expectation was met.
          BufferedSink bufferedRequestBody = Okio.buffer(
              exchange.createRequestBody(request, false));
          request.body().writeTo(bufferedRequestBody);
          bufferedRequestBody.close();
      } else {
        exchange.noRequestBody();
        if (!exchange.connection().isMultiplexed()) {
          // If the "Expect: 100-continue" expectation wasn't met, prevent the HTTP/1 connection
          // from being reused. Otherwise we're still obligated to transmit the request body to
          // leave the connection in a consistent state.
          exchange.noNewExchangesOnConnection();
    } else {
      exchange.noRequestBody();
    if (request.body() == null || !request.body().isDuplex()) {
      //表明完成了http请求request的写入工作
      exchange.finishRequest();
    if (!responseHeadersStarted) {
      exchange.responseHeadersStart();
    if (responseBuilder == null) {
     //读取响应头
      responseBuilder = exchange.readResponseHeaders(false);
    Response response = responseBuilder
        .request(request)
        .handshake(exchange.connection().handshake())
        .sentRequestAtMillis(sentRequestMillis)
        .receivedResponseAtMillis(System.currentTimeMillis())
        .build();
    int code = response.code();
    if (code == 100) {
      // server sent a 100-continue even though we did not request one.
      // try again to read the actual response
      //读取响应头
      response = exchange.readResponseHeaders(false)
          .request(request)
          .handshake(exchange.connection().handshake())
          .sentRequestAtMillis(sentRequestMillis)
          .receivedResponseAtMillis(System.currentTimeMillis())
          .build();
      code = response.code();
    exchange.responseHeadersEnd(response);
    if (forWebSocket && code == 101) {
      // Connection is upgrading, but we need to ensure interceptors see a non-null response body.
      response = response.newBuilder()
          .body(Util.EMPTY_RESPONSE)
          .build();
    } else {
      response = response.newBuilder()
            //读取响应体
          .body(exchange.openResponseBody(response))
          .build();
    if ("close".equalsIgnoreCase(response.request().header("Connection"))
        || "close".equalsIgnoreCase(response.header("Connection"))) {
      exchange.noNewExchangesOnConnection();
    if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
      throw new ProtocolException(
          "HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
    return response;

主要做了几件事

1.Http1ExchangeCodec(http中所有流对象都封装到了Http1ExchangeCodec实现类中),可以简单的理解为它能编码request和解码response

2.exchange.writeRequestHeaders(request);

调用Http1ExchangeCodec的writeRequestHeaders方法写入请求的头部信息

3.写入请求体

BufferedSink bufferedRequestBody = Okio.buffer(
    exchange.createRequestBody(request, false));
request.body().writeTo(bufferedRequestBody);
bufferedRequestBody.close();

4.exchange.finishRequest()表明完成了http请求request的写入工作

5.exchange.readResponseHeaders

读取响应的Header信息

6.exchange.openResponseBody

读取响应的body信息

三、Connection连接相关源码分析

1.Connection接口

package okhttp3;
import java.net.Socket;
import javax.annotation.Nullable;
public interface Connection {
  //返回这个连接使用的Route
  Route route();
  //返回这个连接使用的Socket
  Socket socket();
  //如果是HTTPS,返回TLS握手信息用于连接,否则返回null
  @Nullable Handshake handshake();
  //返回应用层使用的协议,Protocl是个枚举,例如HTTP1.1、HTTP2
  Protocol protocol();

2.RealConnection

成员变量和构造函数

public final class RealConnection extends Http2Connection.Listener implements Connection {
  private static final String NPE_THROW_WITH_NULL = "throw with null exception";
  private static final int MAX_TUNNEL_ATTEMPTS = 21;
  //连接池
  public final RealConnectionPool connectionPool;
  private final Route route;
 //内部使用这个rawSocket在TCP层建立连接
  private Socket rawSocket;
  //如果没有使用HTTPS,那么socket=rawSocket,否则这个socket=SSLSocket
  private Socket socket;
  //TLS握手
  private Handshake handshake;
  //应用层协议
  private Protocol protocol;
  //HTTP2连接
  private Http2Connection http2Connection;
  //okiok库的BufferedSource和BufferSink,相当于javaIO的输入输出流
  private BufferedSource source;
  private BufferedSink sink;
  // The fields below track connection state and are guarded by connectionPool.
   * If true, no new exchanges can be created on this connection. Once true this is always true.
   * Guarded by {@link #connectionPool}.
  boolean noNewExchanges;
   * The number of times there was a problem establishing a stream that could be due to route
   * chosen. Guarded by {@link #connectionPool}.
  int routeFailureCount;
  int successCount;
  private int refusedStreamCount;
   * The maximum number of concurrent streams that can be carried by this connection. If {@code
   * allocations.size() < allocationLimit} then new streams can be created on this connection.
  private int allocationLimit = 1;
  /** Current calls carried by this connection. */
  final List<Reference<Transmitter>> transmitters = new ArrayList<>();
  /** Nanotime timestamp when {@code allocations.size()} reached zero. */
  long idleAtNanos = Long.MAX_VALUE;
  public RealConnection(RealConnectionPool connectionPool, Route route) {
    this.connectionPool = connectionPool;
    this.route = route;

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"));
    } else {
      if (route.address().protocols().contains(Protocol.H2_PRIOR_KNOWLEDGE)) {
        throw new RouteException(new UnknownServiceException(
            "H2_PRIOR_KNOWLEDGE cannot be used with HTTPS"));
     //开始连接
    while (true) {
      try {
        //如果是通道模式,则建立通道连接
        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;
         //否则进行Socket连接,大部分是这种情况
        } else {
          connectSocket(connectTimeout, readTimeout, call, eventListener);
        //建立HTTPS连接
        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();

做了几件事:

1.路由选择

2.开始连接。如果是通道模式,则建立通道连接,否则直接调用connectSocket建立Socket连接,大部分是这种情况。

connectSocket方法

private void connectSocket(int connectTimeout, int readTimeout, Call call,
      EventListener eventListener) throws IOException {
    Proxy proxy = route.proxy();
    Address address = route.address();
     //根据代理类型的不同创建Socket
    rawSocket = proxy.type() == Proxy.Type.DIRECT || proxy.type() == Proxy.Type.HTTP
        ? address.socketFactory().createSocket()
        : new Socket(proxy);
    eventListener.connectStart(call, route.socketAddress(), proxy);
    rawSocket.setSoTimeout(readTimeout);
    try {
      //建立Socket连接
      Platform.get().connectSocket(rawSocket, route.socketAddress(), connectTimeout);
    } catch (ConnectException e) {
      ConnectException ce = new ConnectException("Failed to connect to " + route.socketAddress());
      ce.initCause(e);
      throw ce;
    // The following try/catch block is a pseudo hacky way to get around a crash on Android 7.0
    // More details:
    // https://github.com/square/okhttp/issues/3245
    // https://android-review.googlesource.com/#/c/271775/
    try {
      //获得Socket的输入输出流
      source = Okio.buffer(Okio.source(rawSocket));
      sink = Okio.buffer(Okio.sink(rawSocket));
    } catch (NullPointerException npe) {
      if (NPE_THROW_WITH_NULL.equals(npe.getMessage())) {
        throw new IOException(npe);

做了几件事

1.根据代理类型的不同创建Socket

2.建立Socket连接

Platform的connectSocket方法最终会调用rawSocket的connect()方法建立其Socket连接

3.获得Socket的输入输出流

 3.RealConnectionPool  

成员变量和构造函数 

  //线程池
  private static final Executor executor = new ThreadPoolExecutor(0 /* corePoolSize */,
      Integer.MAX_VALUE /* maximumPoolSize */, 60L /* keepAliveTime */, TimeUnit.SECONDS,
      new SynchronousQueue<>(), Util.threadFactory("OkHttp ConnectionPool", true));
  /** The maximum number of idle connections for each address. */
  private final int maxIdleConnections;
  private final long keepAliveDurationNs;
  //清理连接任务,在executor中执行
  private final Runnable cleanupRunnable = () -> {
    while (true) {
       //调用cleanup方法执行清理逻辑
      long waitNanos = cleanup(System.nanoTime());
      if (waitNanos == -1) return;
      if (waitNanos > 0) {
        long waitMillis = waitNanos / 1000000L;
        waitNanos -= (waitMillis * 1000000L);
        synchronized (RealConnectionPool.this) {
          try {
             //调用wait方法进入等待
            RealConnectionPool.this.wait(waitMillis, (int) waitNanos);
          } catch (InterruptedException ignored) {
  // 双端队列,保存连接
  private final Deque<RealConnection> connections = new ArrayDeque<>();
  final RouteDatabase routeDatabase = new RouteDatabase();
  boolean cleanupRunning;
  public RealConnectionPool(int maxIdleConnections, long keepAliveDuration, TimeUnit timeUnit) {
    this.maxIdleConnections = maxIdleConnections;
    this.keepAliveDurationNs = timeUnit.toNanos(keepAliveDuration);
    // Put a floor on the keep alive duration, otherwise cleanup will spin loop.
    if (keepAliveDuration <= 0) {
      throw new IllegalArgumentException("keepAliveDuration <= 0: " + keepAliveDuration);

put方法

  void put(RealConnection connection) {
    assert (Thread.holdsLock(this));
    if (!cleanupRunning) {
      cleanupRunning = true;
      //使用线程池执行清理任务
      executor.execute(cleanupRunnable);
     //将新建连接插入队列
    connections.add(connection);

主要做了几件事:

1.当第一次调用RealConnectionPool 的put方法缓存新建连接时,如果cleanupRunnable还没执行,它首先会使用线程池执行cleanupRunnable

2.然后把新建连接放入双端队列。

cleanupRunnable中会调用cleanup方法进行连接的清理

cleanup方法

  long cleanup(long now) {
    int inUseConnectionCount = 0;
    int idleConnectionCount = 0;
    RealConnection longestIdleConnection = null;
    long longestIdleDurationNs = Long.MIN_VALUE;
    // Find either a connection to evict, or the time that the next eviction is due.
    synchronized (this) {
       //遍历所有连接,记录空闲连接和正在使用连接各自的数量
      for (Iterator<RealConnection> i = connections.iterator(); i.hasNext(); ) {
        RealConnection connection = i.next();
         //如果该连接还在使用,pruneAndGetAllocationCount种通过引用计数的方式判断一个连接是否空闲
        // If the connection is in use, keep searching.
        if (pruneAndGetAllocationCount(connection, now) > 0) {
          inUseConnectionCount++;
          continue;
        //如果该连接没有在使用,  空闲连接数加1
        idleConnectionCount++;
        //记录keepalive时间最长的那个空闲连接
        // If the connection is ready to be evicted, we're done.
        long idleDurationNs = now - connection.idleAtNanos;
        if (idleDurationNs > longestIdleDurationNs) {
          longestIdleDurationNs = idleDurationNs;
          longestIdleConnection = connection;
      //默认keepalive时间keepAliveDurationNs最长为5分钟,空闲连接数idleConnectionCount最大为5个
      if (longestIdleDurationNs >= this.keepAliveDurationNs
          || idleConnectionCount > this.maxIdleConnections) {
        // We've found a connection to evict. Remove it from the list, then close it below (outside
        // of the synchronized block).
        //如果longestIdleConnection的keepalive时间大于5分钟 或 空闲连接数超过5个
            //把longestIdleConnection连接从队列清理掉
        connections.remove(longestIdleConnection);
      } else if (idleConnectionCount > 0) {
        //如果空闲连接数小于5个 并且 longestIdleConnection连接还没到期清理
            //返回该连接的到期时间,下次再清理
        // A connection will be ready to evict soon.
        return keepAliveDurationNs - longestIdleDurationNs;
      } else if (inUseConnectionCount > 0) {
         //如果没有空闲连接 且 所有连接都还在使用
            //返回keepAliveDurationNs,5分钟后再清理
        // All connections are in use. It'll be at least the keep alive duration 'til we run again.
        return keepAliveDurationNs;
      } else {
         // 没有任何连接,把cleanupRunning复位
        // No connections, idle or in use.
        cleanupRunning = false;
        return -1;
     //把longestIdleConnection连接从队列清理掉后,关闭该连接的socket,返回0,立即再次进行清理
    closeQuietly(longestIdleConnection.socket());
    // Cleanup again immediately.
    return 0;

主要做了几件事

该方法返回现在到下次清理的时间间隔

1.首先遍历所有连接

记录空闲连接数idleConnectionCount和正在使用连接数inUseConnectionCount,在记录空闲连接数时,还要找出空闲时间最长的空闲连接longestIdleConnection,这个连接是很有可能被清理的;

2.遍历完后,根据最大空闲时长和最大空闲连接数来决定是否清理longestIdleConnection

如果longestIdleConnection的空闲时间大于最大空闲时长 或 空闲连接数大于最大空闲连接数,那么该连接就会被从队列中移除,然后关闭该连接的socket,返回0,立即再次进行清理;

如果空闲连接数小于5个 并且 longestIdleConnection的空闲时间小于最大空闲时长即还没到期清理,那么返回该连接的到期时间,下次再清理;

如果没有空闲连接 且 所有连接都还在使用,那么返回默认的keepAlive时间,5分钟后再清理;

如果没有任何连接,idleConnectionCount和inUseConnectionCount都为0,把cleanupRunning复位,等待下一次put连接时,再次使用线程池执行cleanupRunnable。

4.ExchangeFinder

find方法

它是创建连接入口

  public ExchangeCodec find(
      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方法,返回RealConnection
      RealConnection resultConnection = findHealthyConnection(connectTimeout, readTimeout,
          writeTimeout, pingIntervalMillis, connectionRetryEnabled, doExtensiveHealthChecks);
      return resultConnection.newCodec(client, chain);
    } catch (RouteException e) {
      trackFailure();
      throw e;
    } catch (IOException e) {
      trackFailure();
      throw new RouteException(e);

做了几件事

1. 调用findHealthyConnection方法,返回RealConnection

2.调用realConnection.newCodec创建并返回Http1ExchangeCodec(http中所有流对象操作都封装到了Http1ExchangeCodec实现类中)

 findHealthyConnection方法

private RealConnection findHealthyConnection(int connectTimeout, int readTimeout,
      int writeTimeout, int pingIntervalMillis, boolean connectionRetryEnabled,
      boolean doExtensiveHealthChecks) throws IOException {
    //一个死循环
    while (true) {
       //调用findConnection方法,返回RealConnection
      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 && !candidate.isMultiplexed()) {
          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)) {
        candidate.noNewExchanges();
        continue;
      return candidate;

主要做了几件事

1.调用findConnection方法,返回RealConnection

2.判断连接是否可用

3.这是个死循环,只有找到可用的连接realconnection才会返回

findConnection方法

private RealConnection findConnection(int connectTimeout, int readTimeout, int writeTimeout,
      int pingIntervalMillis, boolean connectionRetryEnabled) throws IOException {
    boolean foundPooledConnection = false;
    RealConnection result = null;  //返回结果,可用的连接
    Route selectedRoute = null;
    RealConnection releasedConnection;
    Socket toClose;
    synchronized (connectionPool) {
      if (transmitter.isCanceled()) throw new IOException("Canceled");
      hasStreamFailure = false; // This is a fresh attempt.
      // 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 exchanges.
      //尝试使用已经创建过的连接,已经创建过的连接可能已经被限制创建新的流
      releasedConnection = transmitter.connection;
      //如果已经创建过的连接已经被限制创建新的流,就释放该连接(releaseConnectionNoEvents中会把该连接置空),并返回该连接的Socket以关闭
      toClose = transmitter.connection != null && transmitter.connection.noNewExchanges
          ? transmitter.releaseConnectionNoEvents()
          : null;
      //如果已经创建过的连接还能使用,就直接使用它当作结果、
      if (transmitter.connection != null) {
        // We had an already-allocated connection and it's good.
        result = transmitter.connection;
        releasedConnection = null;
      //如果已经创建过的连接不能使用
      if (result == null) {
        //尝试从连接池中找可用的连接,如果找到,这个连接会赋值先保存在Transmitter中
        // Attempt to get a connection from the pool.
        if (connectionPool.transmitterAcquirePooledConnection(address, transmitter, null, false)) {
          //从连接池中找到可用的连接
          foundPooledConnection = true;
          result = transmitter.connection;
        } else if (nextRouteToTry != null) {
          selectedRoute = nextRouteToTry;
          nextRouteToTry = null;
        } else if (retryCurrentRoute()) {
          selectedRoute = transmitter.connection.route();
    closeQuietly(toClose);
    if (releasedConnection != null) {
      eventListener.connectionReleased(call, releasedConnection);
    if (foundPooledConnection) {
      eventListener.connectionAcquired(call, result);
    if (result != null) {
       //如果在上面已经找到了可用连接,直接返回结果
      // If we found an already-allocated or pooled connection, we're done.
      return result;
    //走到这里没有找到可用连接,看看是否需要路由选择,多IP操作
    // If we need a route selection, make one. This is a blocking operation.
    boolean newRouteSelection = false;
    if (selectedRoute == null && (routeSelection == null || !routeSelection.hasNext())) {
      newRouteSelection = true;
      routeSelection = routeSelector.next();
    List<Route> routes = null;
    synchronized (connectionPool) {
      if (transmitter.isCanceled()) 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.
        routes = routeSelection.getAll();
        //这里第二次尝试从连接池中找可用连接
        if (connectionPool.transmitterAcquirePooledConnection(
            address, transmitter, routes, false)) {
          //从连接池中找到可用的连接
          foundPooledConnection = true;
          result = transmitter.connection;
       //在连接池中没有找到可用连接
      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.
        //所以这里新创建一个连接,后面会进行Socket连接
        result = new RealConnection(connectionPool, selectedRoute);
        connectingConnection = result;
    // 如果在连接池中找到可用的连接,直接返回该连接
    // If we found a pooled connection on the 2nd time around, we're done.
    if (foundPooledConnection) {
      eventListener.connectionAcquired(call, result);
      return result;
    // 调用RealConnection的connect方法进行Socket连接,这个在RealConnection中讲过
    // Do TCP + TLS handshakes. This is a blocking operation.
    result.connect(connectTimeout, readTimeout, writeTimeout, pingIntervalMillis,
        connectionRetryEnabled, call, eventListener);
    connectionPool.routeDatabase.connected(result.route());
    Socket socket = null;
    synchronized (connectionPool) {
      connectingConnection = null;
      // Last attempt at connection coalescing, which only occurs if we attempted multiple
      // concurrent connections to the same host.
      // 如果我们刚刚创建了同一地址的多路复用连接,释放这个连接并获取那个连接
      if (connectionPool.transmitterAcquirePooledConnection(address, transmitter, routes, true)) {
        // We lost the race! Close the connection we created and return the pooled connection.
        result.noNewExchanges = true;
        socket = result.socket();
        result = transmitter.connection;
        // It's possible for us to obtain a coalesced connection that is immediately unhealthy. In
        // that case we will retry the route we just successfully connected with.
        nextRouteToTry = selectedRoute;
      } else {
        // 把刚刚新建的连接放入连接池
        connectionPool.put(result);
        // 把刚刚新建的连接保存到Transmitter的connection字段
        transmitter.acquireConnectionNoEvents(result);
    closeQuietly(socket);
    eventListener.connectionAcquired(call, result);
    return result;

主要做了几件事

1.尝试使用已经创建过的连接,已经创建过的连接可能已经被限制创建新的流

2.如果已经创建过的连接已经被限制创建新的流,就释放该连接(releaseConnectionNoEvents中会把该连接置空),并返回该连接的Socket以关闭

3.如果已经创建过的连接还能使用,就直接使用它当作结果、

4.如果已经创建过的连接不能使用

尝试从连接池中找可用的连接,如果找到,这个连接会赋值先保存在Transmitter中

5.如果无法使用已经创建过的连接

看看是否需要路由选择,多IP操作。

如果有下一个路由,第二次尝试从连接池中找可用连接。

如果在连接池中没有找到可用连接,新创建一个连接,后面会进行Socket连接

6.调用RealConnection的connect方法进行Socket连接,这个在RealConnection中讲过

7.如果我们刚刚创建了同一地址的多路复用连接,释放这个连接并获取那个连接。

否则把刚刚新建的连接放入连接池、保存到Transmitter的connection字段

 大概过程如下图:

okhttp3版本3.14.9一、简介1.请求流程图发出请求前,会经过interceptorChain,拦截链2.常见的拦截链有RetryAndFollowUpInterceptor重试与重定向拦截器用来实现重试和重定向功能,内部通过while(true)死循环来进行重试获取Response(有重试上限,超过会抛出异常)。followUpRequest主要用来根据响应码来判断属于哪种行为触发的重试和重定向(比如未授权,超时,重定向等),然后构建响应的Request进行下. OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args); 代码很简单,那我们就来探究下这个OkHttpCall能干什么: final class OkHttpCall<T> impleme 使用OkHttp3发送Http请求并获得响应的过程大体为: 创建OkHttpClient对象。OkHttpClient为网络请求执行的一个中心,它会管理连接池,缓存,SocketFactory,代理,各种超时时间,DNS,请求执行结果的分发等许多内容。 创建Request对象。Request用于描述一个HTTP请求,比如请求的方法是"GET"还是"POST",请求的UR
前言:应用程序需要发送网络请求服务器的接口,可使用OkHttp 3发送请求获取服务端数据 GitHut地址 Step 1:申请网络请求的权限:在manifests层的AndroidManifest.xml里的 <manifest控件里添加: <!--允许程序打开网络套接字--> <uses-permission android:name="android.permission.INTERNET" /> Step 2:引入依赖:在Gradle Scripts层的
retrofit是一款好用的http框架,在项目集成retrofit时,有时候会启动报关于okhttp错,如下: the follollowing method did not exists: okhttp3.HttpUrl.get(Ljava/lang/String;)Lokhttp3/HttpUrl; 解决思路: 排除retrofit 的okhttp3依赖,强依赖okhttp3 3.12.0版本 <dependency> <groupId>com.g...
错误出现的场景描述 我们的项目中使用了Retrofit 结合 RxJava、RxAndroid 调用后台接口,在 Retrofit 中有个拦截器,去拦截打印log 信息。当调用 chain.proceed(newRequest) 方法的时候出现上述错误。 这不是个必现的错误。只是调用某些接口才会出现。从Retrofit 的源码可以知道。当 Retrofit 的网络请求未完成,而观察者已经取...
从左到右遍历A[]时,对于相同值元素A[j],是按照从右往左依次填充至result[]中的,这样A中的相同元素就会逆序填充到res数组中。 因此正确的做法应该是,修改第27行,从右到左遍历A[] for (int j=A.length-1; j>=0; j--) { 【十八】常见十种排序算法总结笔记 程序猿皮卡丘: 查了一下相关资料,发现希尔排序有很多种关于间隔interval的实现方法,其平均/最坏时间复杂度,和具体的每种实现方法有关。比如原始方法(k=k/2),时间复杂度最坏为O(n2),而高德纳knuth方法(h=(3^k-1)/2),时间复杂度最坏为O(n^1.5),Pratt方法(h=2^p*3^q),时间复杂度最坏为O(n*(logn)^2)。因此关于希尔排序的时间复杂度,其实并没有一个统一的结论。 【十八】常见十种排序算法总结笔记 程序猿皮卡丘: 另外希尔排序的最好时间复杂度应该统一为O(nlogn),楼主表格中写的时O(n(logn)2)感觉不太准确。 【十八】常见十种排序算法总结笔记 程序猿皮卡丘: 请问下楼主,表格中希尔排序的平均时间复杂度是O(nlogn),但最好/最坏情况的时间复杂度却都是O(nlogn2),也就是O(nlogn2)<O(nlogn)<O(nlogn2)?这里是不是写的有点问题?还是我理解有误?麻烦指点一下,谢谢。 VMware下的Centos7操作(NAT固定IP、开始SSH服务、开启远程ROOT密码登录) 自启动列表在哪?