OKHttp源码分析拦截器-RetryAndFollowUpInterceptor

这里写图片描述
继上一篇博客我们继续分析okhttp这里我们要着重分析的是okhttp的拦截器。
RetryAndFollowUpInterceptor主要完成的工作为

  1. 初始化StreamAllocation通过StreamAllocation创建一个连接对象
  2. 调用realChain.proceed丢给下一个拦截器处理请求的内容
  3. 捕获异常对处理后的内容做进一步的分析处理

我们首先来看OKhttp的第一层拦截器RetryAndFollowUpInterceptor(其实也不能完说第一层因为我们自定义的拦截器是走在第一层的,当我们不设置自己的拦截器的时候RetryAndFollowUpInterceptor是我们的第一层拦截器)
拦截器的其他方法我们就不在做过多的说明了这里我们着重分析intercept这个方法代码如下。

@Override public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Call call = realChain.call();
    EventListener eventListener = realChain.eventListener();
    //初始化一个socket连接对象
    streamAllocation = new StreamAllocation(client.connectionPool(), createAddress(request.url()),
            call, eventListener, callStackTrace);

    int followUpCount = 0;
    Response priorResponse = null;
    while (true) {
      // 一个死循环 ,重试, 两种情况可以终止 return Response, throws IOException
      if (canceled) {
        streamAllocation.release();
        throw new IOException("Canceled");
      }

      Response response;
      boolean releaseConnection = true;
      try {
        // 丢给下一个拦截器去处理,会有异常的情况
        response = realChain.proceed(request, streamAllocation, null, null);
        releaseConnection = false;
      } catch (RouteException e) {
        // The attempt to connect via a route failed. The request will not have been sent.
        // 先处理 RouteException
        if (!recover(e.getLastConnectException(), false, request)) {
          throw e.getLastConnectException();
        }
        releaseConnection = false;
        continue;
      } catch (IOException e) {
        // 处理 IOException
        // An attempt to communicate with a server failed. The request may have been sent.
        boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
        if (!recover(e, requestSendStarted, request)) throw e;
        releaseConnection = false;
        continue;
      } finally {
        // We're throwing an unchecked exception. Release any resources.
        if (releaseConnection) {
          streamAllocation.streamFailed(null);
          streamAllocation.release();
        }
      }

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

      // 从下面过了一个 Response ,但是这个 Response 不能够直接返回给上一级,会有重定向
      // 重定向 返回码是 307 ,从头部的 Location 里面获取新的链接 重新请求一次
      Request followUp = followUpRequest(response);

      if (followUp == null) {
        if (!forWebSocket) {
          streamAllocation.release();
        }
        // 直接返回给上一级
        return response;
      }

      closeQuietly(response.body());

      if (++followUpCount > MAX_FOLLOW_UPS) {
        streamAllocation.release();
        throw new ProtocolException("Too many follow-up requests: " + followUpCount);
      }

      if (followUp.body() instanceof UnrepeatableRequestBody) {
        streamAllocation.release();
        throw new HttpRetryException("Cannot retry streamed HTTP body", response.code());
      }

      if (!sameConnection(response, followUp.url())) {
        streamAllocation.release();
        streamAllocation = new StreamAllocation(client.connectionPool(),
            createAddress(followUp.url()), call, eventListener, callStackTrace);
      } else if (streamAllocation.codec() != null) {
        throw new IllegalStateException("Closing the body of " + response
            + " didn't close its backing stream. Bad interceptor?");
      }

      // 请求就变为了重试的请求 Request
      request = followUp;
      priorResponse = response;
    }
  }

我们先看代码执行第一步初始化连接对象,通过OKIo拿到连接对象。

// 初始化一个Socket连接对象,此处是第一步,然后获取输入/输出流(连接池,连接线路Address,请求对象,一些其他参数)
streamAllocation = new StreamAllocation(client.connectionPool(), createAddress(request.url()),
            call, eventListener, callStackTrace);

我们分析下StreamAllocation是如何创建连接的

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 {
      // 找一个连接,首先判断有没有健康的,没有就创建(建立Scoket,握手连接),连接缓存
      RealConnection resultConnection = findHealthyConnection(connectTimeout, readTimeout,
          writeTimeout, connectionRetryEnabled, doExtensiveHealthChecks);
      // 封装 HttpCodec 里面封装了 okio 的 Source(输入) 和 Sink (输出)
      HttpCodec resultCodec = resultConnection.newCodec(client, chain, this);
      synchronized (connectionPool) {
        codec = resultCodec;
        return resultCodec;
      }
    } catch (IOException e) {
      throw new RouteException(e);
    }
  }

findHealthyConnection这个方法没啥可说的就是调用findConnection方法循环连接池知道找到健康的RealConnection并返回如果没有则创建一个连接(为了避免大家懵逼就不过多对这一块儿内容做过多细说了)
resultConnection.newCodec这个处理我们可以看看
这个处理是在我们的RealConnection中去处理的代码如下

 public HttpCodec newCodec(OkHttpClient client, Interceptor.Chain chain,
      StreamAllocation streamAllocation) throws SocketException {
    if (http2Connection != null) {
      return new Http2Codec(client, chain, streamAllocation, http2Connection);
    } else {
      socket.setSoTimeout(chain.readTimeoutMillis());
      // Okio : 基于原生的IO的封装 ,IO涉及类和方法忒多,source(输入) sink(输出)
      source.timeout().timeout(chain.readTimeoutMillis(), MILLISECONDS);
      sink.timeout().timeout(chain.writeTimeoutMillis(), MILLISECONDS);
      // Http1Codec 就是 封装了 source 和 sink 就是自己的输入输出流,本质就是操作 Socket 的输入输出流
      return new Http1Codec(client, streamAllocation, source, sink);
    }
  }

从这里我们可以看出okhttp处理链接的核心是socket+Okio实现的也就是说OKHttp的处理不是基于现成的HttpURLconnection实现的而是基于socket+Okio 因为高效的OKio所以okhttp要比我们传统的HttpURLconnection要快。回到我们的正题这一步还是封装我们的请求Codec并未发送请求。
再回到我们的最初的位置StreamAllocation完成了我们的请求请求对象的初始化获得了一个socket连接对象。
我们再看后面的拦截处理
接下来我们再分析下面的那个while死循环
从下面的处理我们可以看出有两种情况可以跳出循环抛出异常或者返回响应

if (canceled) {
        streamAllocation.release();
        throw new IOException("Canceled");
      }

这段代码没啥可说的如果请求取消了抛出异常结束循环。

 Response response;
      boolean releaseConnection = true;
      try {
        // 丢给下一个拦截器去处理,会有异常的情况
        response = realChain.proceed(request, streamAllocation, null, null);
        releaseConnection = false;
      }

如果说上面创建streamAllocation这个链接对象是该拦截器的第一步主要工作那么realChain.proceed则是这个拦截器第二部主要工作,到这一段代码开始这个拦截器的准备工作已经处理完成了,下面的工作就是其他拦截器处理完内容后该拦截器才会处理的内容,这也是责任链模式的一个很重要的应用,我们继续看下面的处理。

} catch (RouteException e) {
        // The attempt to connect via a route failed. The request will not have been sent.
        // 先处理 RouteException
        if (!recover(e.getLastConnectException(), false, request)) {
          throw e.getLastConnectException();
        }
        releaseConnection = false;
        continue;
      }

这段处理的是路由异常我们在看recover这个方法

private boolean recover(IOException e, boolean requestSendStarted, Request userRequest) {
    streamAllocation.streamFailed(e);

    // The application layer has forbidden retries.
    if (!client.retryOnConnectionFailure()) return false;

    // We can't send the request body again.
    if (requestSendStarted && userRequest.body() instanceof UnrepeatableRequestBody) return false;

    // This exception is fatal. 是不是致命异常
    if (!isRecoverable(e, requestSendStarted)) return false;

    // No more routes to attempt.
    if (!streamAllocation.hasMoreRoutes()) return false;

    // For failure recovery, use the same route selector with a new connection.
    return true;
  }

意思很明白是通过处理判断该异常是否是致命的是否可以继续发送请求,如果不是致命的则continue继续发送请求。

再看下面的IO异常的处理

catch (IOException e) {
        // 处理 IOException
        // An attempt to communicate with a server failed. The request may have been sent.
        boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
        if (!recover(e, requestSendStarted, request)) throw e;
        releaseConnection = false;
        continue;
      } 

跟上面的异常处理类似这里就不多说了。最终调用我们的finally处理

finally {
        // We're throwing an unchecked exception. Release any resources.
        if (releaseConnection) {
          streamAllocation.streamFailed(null);
          streamAllocation.release();
        }

这段意思是抛出了其他的异常就回收socket链接。

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

这段意思是好像发送请求没有请求体我没见到过这样的请求不知道大家有没有捡到过。我们接下来分析。

 // 从下面过了一个 Response ,但是这个 Response 不能够直接返回给上一级,会有重定向
      // 重定向 返回码是 307 ,从头部的 Location 里面获取新的链接 重新请求一次
      Request followUp = followUpRequest(response);

      if (followUp == null) {
        if (!forWebSocket) {
          streamAllocation.release();
        }
        // 直接返回给上一级
        return response;
      }

这里是对请求的请求码做判断如果是重定向需要重新处理请求内容再次发送请求,如果不是那么调用 streamAllocation.release()将socket链接关闭返回响应终止循环。
我们来看看followUpRequest这个方法的处理

private Request followUpRequest(Response userResponse) throws IOException {
    if (userResponse == null) throw new IllegalStateException();
    Connection connection = streamAllocation.connection();
    Route route = connection != null
        ? connection.route()
        : null;
    int responseCode = userResponse.code();

    final String method = userResponse.request().method();
    // 对状态码进行判断

    switch (responseCode) {
      case HTTP_PROXY_AUTH:
        Proxy selectedProxy = route != null
            ? route.proxy()
            : client.proxy();
        if (selectedProxy.type() != Proxy.Type.HTTP) {
          throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy");
        }
        return client.proxyAuthenticator().authenticate(route, userResponse);

      case HTTP_UNAUTHORIZED:
        return client.authenticator().authenticate(route, userResponse);

      case HTTP_PERM_REDIRECT:
      case HTTP_TEMP_REDIRECT:
        // "If the 307 or 308 status code is received in response to a request other than GET
        // or HEAD, the user agent MUST NOT automatically redirect the request"
        if (!method.equals("GET") && !method.equals("HEAD")) {
          return null;
        }
        // fall-through
      case HTTP_MULT_CHOICE:
      case HTTP_MOVED_PERM:
      case HTTP_MOVED_TEMP:
      case HTTP_SEE_OTHER:
        // Does the client allow redirects?
        if (!client.followRedirects()) return null;
        // 从头部信息里面 获取 Location 新的链接
        String location = userResponse.header("Location");
        if (location == null) return null;
        // 生成一个新的 HttpUrl
        HttpUrl url = userResponse.request().url().resolve(location);

        // Don't follow redirects to unsupported protocols.
        if (url == null) return null;

        // If configured, don't follow redirects between SSL and non-SSL.
        boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());
        if (!sameScheme && !client.followSslRedirects()) return null;

        // Most redirects don't include a request body.
        Request.Builder requestBuilder = userResponse.request().newBuilder();
        if (HttpMethod.permitsRequestBody(method)) {
          final boolean maintainBody = HttpMethod.redirectsWithBody(method);
          if (HttpMethod.redirectsToGet(method)) {
            requestBuilder.method("GET", null);
          } else {
            RequestBody requestBody = maintainBody ? userResponse.request().body() : null;
            requestBuilder.method(method, requestBody);
          }
          if (!maintainBody) {
            requestBuilder.removeHeader("Transfer-Encoding");
            requestBuilder.removeHeader("Content-Length");
            requestBuilder.removeHeader("Content-Type");
          }
        }

        // When redirecting across hosts, drop all authentication headers. This
        // is potentially annoying to the application layer since they have no
        // way to retain them.
        if (!sameConnection(userResponse, url)) {
          requestBuilder.removeHeader("Authorization");
        }
        // 返回一个新链接的 Request
        return requestBuilder.url(url).build();

      case HTTP_CLIENT_TIMEOUT:
        // 408's are rare in practice, but some servers like HAProxy use this response code. The
        // spec says that we may repeat the request without modifications. Modern browsers also
        // repeat the request (even non-idempotent ones.)
        if (!client.retryOnConnectionFailure()) {
          // The application layer has directed us not to retry the request.
          return null;
        }

        if (userResponse.request().body() instanceof UnrepeatableRequestBody) {
          return null;
        }

        if (userResponse.priorResponse() != null
            && userResponse.priorResponse().code() == HTTP_CLIENT_TIMEOUT) {
          // We attempted to retry and got another timeout. Give up.
          return null;
        }

        return userResponse.request();

      default:
        return null;
    }
  }

这里我们看到如果是重定向的就会重新处理请求的参数并配置好请求内容。

   //如果是需要再次处理的请求关闭响应体
   closeQuietly(response.body());、
   //是否超过最大重新请求限制了
   if (++followUpCount > MAX_FOLLOW_UPS) {
        streamAllocation.release();
        throw new ProtocolException("Too many follow-up requests: " + followUpCount);
      }
      //如果请求体为不可重复发送请求体抛出异常
      if (followUp.body() instanceof UnrepeatableRequestBody) {
        streamAllocation.release();
        throw new HttpRetryException("Cannot retry streamed HTTP body", response.code());
      }

      if (!sameConnection(response, followUp.url())) {
        streamAllocation.release();
        streamAllocation = new StreamAllocation(client.connectionPool(),
            createAddress(followUp.url()), call, eventListener, callStackTrace);
      } else if (streamAllocation.codec() != null) {
        throw new IllegalStateException("Closing the body of " + response
            + " didn't close its backing stream. Bad interceptor?");
      }

      // 请求就变为了重试的请求 Request
      request = followUp;
      priorResponse = response;

到此我们的RetryAndFollowUpInterceptor拦截器处理就结束了,不得不说这里面的处理确实挺多的大家可以参照我的解析重新对照源码分析一遍。

猜你喜欢

转载自blog.csdn.net/u011048906/article/details/79582344