相关文章推荐
暴走的烤地瓜  ·  json.decoder.JSONDecod ...·  1 月前    · 
睡不着的卡布奇诺  ·  Android中使用OkHttp3无法获取响 ...·  2 周前    · 
唠叨的紫菜汤  ·  okhttp——RetryAndFollow ...·  4 天前    · 
乖乖的韭菜  ·  获取"Index超出了数组的界限“。同时调用 ...·  2 年前    · 
怕老婆的沙发  ·  H5播放HLS视频时请求两次M3U8,第一次 ...·  2 年前    · 
豪情万千的双杠  ·  Python调用shell命令常用方法(4种 ...·  3 年前    · 
Code  ›  okhttp——RetryAndFollowUpInterceptor开发者社区
response
https://cloud.tencent.com/developer/article/1426112
唠叨的紫菜汤
4 天前
Oceanlong

okhttp——RetryAndFollowUpInterceptor

腾讯云
开发者社区
文档 建议反馈 控制台
首页
学习
活动
专区
圈层
工具
MCP广场
文章/答案/技术大牛
发布
Oceanlong
社区首页 > 专栏 > okhttp——RetryAndFollowUpInterceptor

okhttp——RetryAndFollowUpInterceptor

作者头像
Oceanlong
发布 于 2019-05-15 10:42:27
发布 于 2019-05-15 10:42:27
1.8K 0
举报
文章被收录于专栏: 移动开发面面观 移动开发面面观

简介

okhttp的网络请求采用interceptors链的模式。每一级interceptor只处理自己的工作,然后将剩余的工作,交给下一级interceptor。本文将主要阅读 okhttp 中的 RetryAndFollowUpInterceptor ,了解它的作用和工作原理。

RetryAndFollowUpInterceptor

顾名思义, RetryAndFollowUpInterceptor 负责okhttp的请求失败的恢复和重定向。

核心的 intercept 方法分两段阅读:

代码语言: javascript
复制
  @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) {
      transmitter.prepareToConnect(request);
      if (transmitter.isCanceled()) {
        throw new IOException("Canceled");
      Response response;
      boolean success = false;
      try {
        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);
        if (!recover(e, transmitter, requestSendStarted, request)) throw e;
        continue;
      } finally {
        // The network call threw an exception. Release any resources.
        if (!success) {
          transmitter.exchangeDoneDueToException();
  }

前半段的逻辑中, RetryAndFollowUpInterceptor 做了几件事:

  • 通过 Transmitter 准备连接
  • 执行请求链下一级
  • 处理了下一级请求链中的 RouteException 和 IOException 。

Transmitter 的实现,以后的章节再单独讲解。此处略过。我们重点看一下, RetryAndFollowUpInterceptor 如何处理两个异常。

RouteException

从注释中,我们可以看到,RouteException表示客户端连接路由失败。此时会调用 recover 方法,如果recover方法再失败,会抛出RouteException中的 FirstConnectException 。

我们看一下 recover 方法的实现:

代码语言: javascript
复制
  /**
   * Report and attempt to recover from a failure to communicate with a server. Returns true if
   * {@code e} is recoverable, or false if the failure is permanent. Requests with a body can only
   * be recovered if the body is buffered or if the failure occurred before the request has been
   * sent.
  private boolean recover(IOException e, Transmitter transmitter,
      boolean requestSendStarted, Request userRequest) {
    // The application layer has forbidden retries.
    if (!client.retryOnConnectionFailure()) return false;
    // We can't send the request body again.
    if (requestSendStarted && requestIsOneShot(e, userRequest)) return false;
    // This exception is fatal.
    if (!isRecoverable(e, requestSendStarted)) return false;
    // No more routes to attempt.
    if (!transmitter.canRetry()) return false;
    // For failure recovery, use the same route selector with a new connection.
    return true;
  }

首先我们调用应用层的失败回调,如果应用层返回false,就不再进行重试。

然后,我们判断请求的返回,如果请求已经开始或请求限定,只能请求一次,我们也不再进行重试。其中,只能请求一次,可能是客户端自行设定的,也可能是请求返回了 404 。明确告知了文件不存在,也不会再重复请求。

接下来,是okhttp认为的致命错误,不会再重复请求的,都会在 isRecoverable 方法中。致命错误包括:协议错误、SSL校验错误等。

代码语言: javascript
复制
  private boolean isRecoverable(IOException e, boolean requestSendStarted) {
    // If there was a protocol problem, don't recover.
    if (e instanceof ProtocolException) {
      return false;
    // If there was an interruption don't recover, but if there was a timeout connecting to a route
    // we should try the next route (if there is one).
    if (e instanceof InterruptedIOException) {
      return e instanceof SocketTimeoutException && !requestSendStarted;
    // Look for known client-side or negotiation errors that are unlikely to be fixed by trying
    // again with a different route.
    if (e instanceof SSLHandshakeException) {
      // If the problem was a CertificateException from the X509TrustManager,
      // do not retry.
      if (e.getCause() instanceof CertificateException) {
        return false;
    if (e instanceof SSLPeerUnverifiedException) {
      // e.g. a certificate pinning error.
      return false;
    // An example of one we might want to retry with a different route is a problem connecting to a
    // proxy and would manifest as a standard IOException. Unless it is one we know we should not
    // retry, we return true and try a new route.
    return true;
  }

最后,在底层中寻找是否还有其他的 Router 可以尝试。

IOException

IOException表示连接已经建立,但读取内容时失败了。我们同样会进行 recover 尝试,由于代码逻辑一样,不再重复阅读。

在finally中, Transmitter 会释放所有资源。


followUpRequest

接下来,我们看一下 RetryAndFollowUpInterceptor 中 intercept 后半段的实现:

代码语言: javascript
复制
  @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) {
      // 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 followUp = followUpRequest(response, route);
      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();
      if (++followUpCount > MAX_FOLLOW_UPS) {
        throw new ProtocolException("Too many follow-up requests: " + followUpCount);
      request = followUp;
      priorResponse = response;
  }

我们拆开来看这段复杂的逻辑。大体上来说,这段逻辑主要是通过上次请求的返回,生成 followUp 。然后根据 followUp 的内容,判断是不是有效的返回。如果返回是有效的,就直接return请求的返回。如果返回无效,则 request=followUp ,重走while循环,重新请求。

所以这一段的核心逻辑在于 followUpRequest 方法。我们来看下 followUpRequest 的实现。

代码语言: javascript
复制
  /**
   * Figures out the HTTP request to make in response to receiving {@code userResponse}. This will
   * either add authentication headers, follow redirects or handle a client request timeout. If a
   * follow-up is either unnecessary or not applicable, this returns null.
  private Request followUpRequest(Response userResponse, @Nullable Route route) throws IOException {
    if (userResponse == null) throw new IllegalStateException();
    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;
        String location = userResponse.header("Location");
        if (location == null) return null;
        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.request().url(), url)) {
          requestBuilder.removeHeader("Authorization");
        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;
        RequestBody requestBody = userResponse.request().body();
        if (requestBody != null && requestBody.isOneShot()) {
          return null;
        if (userResponse.priorResponse() != null
            && userResponse.priorResponse().code() == HTTP_CLIENT_TIMEOUT) {
          // We attempted to retry and got another timeout. Give up.
          return null;
        if (retryAfter(userResponse, 0) > 0) {
          return null;
        return userResponse.request();
      case HTTP_UNAVAILABLE:
        if (userResponse.priorResponse() != null
            && userResponse.priorResponse().code() == HTTP_UNAVAILABLE) {
          // We attempted to retry and got another timeout. Give up.
          return null;
        if (retryAfter(userResponse, Integer.MAX_VALUE) == 0) {
          // specifically received an instruction to retry without delay
          return userResponse.request();
 
推荐文章
暴走的烤地瓜  ·  json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) - 找回失去的自我
1 月前
睡不着的卡布奇诺  ·  Android中使用OkHttp3无法获取响应问题求助
2 周前
唠叨的紫菜汤  ·  okhttp——RetryAndFollowUpInterceptor开发者社区
4 天前
乖乖的韭菜  ·  获取"Index超出了数组的界限“。同时调用EnvDTE80.ErrorItems.item()-腾讯云开发者社区-腾讯云
2 年前
怕老婆的沙发  ·  H5播放HLS视频时请求两次M3U8,第一次CDN已返回全量,第二次还请求range不为0的m3u8 | 微信开放社区
2 年前
豪情万千的双杠  ·  Python调用shell命令常用方法(4种) - 腾讯云开发者社区-腾讯云
3 年前
今天看啥   ·   Py中国   ·   codingpro   ·   小百科   ·   link之家   ·   卧龙AI搜索
删除内容请联系邮箱 2879853325@qq.com
Code - 代码工具平台
© 2024 ~ 沪ICP备11025650号