OKHTTP深入浅出(四)----拦截器(1)RetryAndFollowUpInterceptor

上一篇分析OKHTTP的整体流程,OKHTTP深入浅出(三)----源码流程_王胖子总叫我减肥的博客-CSDN博客

 我们了解到OK的网络请求真正是通过拦截器链关联的各个拦截器进行处理的,先回顾一下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));
    interceptors.add(new BridgeInterceptor(client.cookieJar()));
    interceptors.add(new CacheInterceptor(client.internalCache()));
    interceptors.add(new ConnectInterceptor(client));
    if (!forWebSocket) {
      interceptors.addAll(client.networkInterceptors());
    }
    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);
      }
    }
  }

       首先构建了一个ArrayList集合,然后将client.interceptors()(自定义的拦截器)、RetryAndFollowUpInterceptor(重试和跟进拦截器)、BridgeInterceptor(桥拦截器)、CacheInterceptor(缓存拦截器)、ConnectInterceptor(连接拦截器)、CallServerInterceptor(请求拦截器)加入到集合中。

      然后构建一个新的拦截器链,参入刚才构建的拦截器集合、发射器、index、请求等

Interceptor.Chain chain = new RealInterceptorChain(interceptors, transmitter, null, 0,
        originalRequest, this, client.connectTimeoutMillis(),
        client.readTimeoutMillis(), client.writeTimeoutMillis());

核心是调用构建的拦截器链RealInterceptorChain的proceed方法,并将返回结果Response返回,再回顾一下这个proceed方法。

这个方法一开始在Interceptor拦截器接口定义

在RealInterceptorChain中实现了Interceptor拦截器接口中的proceed()方法

 @Override public Response proceed(Request request) throws IOException {
    return proceed(request, transmitter, exchange);
  }

深入看一下proceed()方法做了什么?

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

 首先判断 index >= interceptors.size(),这个上篇文章已经详细介绍过,意思大概就是我们下面要在拦截器链中取具体拦截器的时候,要保证index不越界,就说要取的拦截器要在拦截器链中。

下面看一下proceed的核心方法。

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

    又新建了一个新的拦截器链,和上个拦截器链相比,构造方法中的参数只有一个发生了变化index变成了index + 1,也就是说新建的拦截器链比上个拦截器链少了一个拦截器,为什么要这么做呢?肯定是要这个少的拦截器,之后,可以看到,从之前的拦截器集合中,取出了第一个拦截器,并且调用了该拦截器的intercept(next)方法,参数next就是我们刚刚新构建的拦截器链。

    再深入看一下interceptor.intercept(next) 方法,发现这个intercept()方法又是定义在Interceptor接口中的抽象方法。看看哪些类实现了这个抽象方法?

 很明显实现了 intercept()抽象方法就是我们在一开始看到加入到拦截器集合的各个拦截器。

那我们就一个个的看一下,在具体的拦截器中,intercept方法都做了什么?

1、RetryAndFollowUpInterceptor 重试和跟进拦截器

此拦截器从故障中恢复并根据需要遵循重定向。 如果调用被取消,它可能会抛出一个 IOException。

@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) {
      // 1
      // 准备连接请求
      // 主机、端口、协议都相同时,连接可复用
      transmitter.prepareToConnect(request);

      if (transmitter.isCanceled()) {
        throw new IOException("Canceled");
      }

      Response response;
      boolean success = false;
      try {
        // 2 
        // 执行其他(下一个->下一个->...)拦截器的功能,获取Response;
        response = realChain.proceed(request, transmitter, null);
        success = true;
      } catch (RouteException e) {
        // 3
        // 连接路由异常,此时请求还未发送。尝试恢复
        // 返回true,continue,继续下一个while循环
        // 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) {
        // 4
         // IO异常,请求可能已经发出。尝试恢复
        // 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 {
          // 5
         // 请求没成功,释放资源     
        // 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;
      // 6
      // 后面的拦截器执行完了,拿到Response
      // 解析看下是否需要重试或重定向,需要则返回新的Request 
      Request followUp = followUpRequest(response, route);

      if (followUp == null) {
        if (exchange != null && exchange.isDuplex()) {
          transmitter.timeoutEarlyExit();
        }
        // 如果followUpRequest返回的Request为空,那边就表示不需要执行重试或者重定向,直接返回数据
        return response;
      }

      RequestBody followUpBody = followUp.body();
      if (followUpBody != null && followUpBody.isOneShot()) {
        // 如果followUp不为null,请求体不为空,但只需要请求一次时,那么就返回response;
        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;
    }
  }

   先是获取请求、发射器,然后进入While循环,循环的意义在于如果是重试或者重定向,就执行一遍这个过程,否则的话,就通过return返回或者throw跳出循环。

注释1,transmitter.prepareToConnect(request),开始准备连接。transmitter(发射器)是应用层和网络层的桥梁,在真正进行连接、请求、获取响应的时候起重要作用。

  深入看一下,是怎么进行准备连接的,大致就是新建一个新的ExchangeFinder赋值给transmitter(如果transmitter不存在ExchangeFinder)。

  public void prepareToConnect(Request request) {
    if (this.request != null) {
      if (sameConnection(this.request.url(), request.url()) && exchangeFinder.hasRouteToTry()) {
        return; // Already ready.
      }
      if (exchange != null) throw new IllegalStateException();

      if (exchangeFinder != null) {
        maybeReleaseConnection(null, true);
        exchangeFinder = null;
      }
    }

    this.request = request;
    //connectionPool是在OkHttpClient.Build->new ConnectionPool->new RealConnectionPool创建的
   //createAddress方法返回的Address
    this.exchangeFinder = new ExchangeFinder(this, connectionPool, createAddress(request.url()),
        call, eventListener);
  }

    首先看看是否有相同的已存在的transmitter,没有就新创建一个ExchangeFinder,目的是为了获取连接做准备,ExchangeFinder是交换查找器,作用是获取请求的连接。 

回到主流程,注释2,response = realChain.proceed(request, transmitter, null); 调用拦截器的proceed()方法,获取Response。这个方法是不是特别熟悉?没错就是:

Public Response proceed(Request request, Transmitter transmitter, @Nullable Exchange exchange)
  ....

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

。。。。。

    return response;
  }

这就是责任链模式。总结一下,就是注释2,主要的作用就是调用拦截器链的proceed方法,将请求传递给下一个拦截器,尝试从下一个拦截器中获取Response。

   如果注释2处的过程,发生了连接路由异常、IO异常,就由注释3和4处的recover()方法判断是否需要进行重试,看一下recover()方法怎么判断的?

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

   上面的条件1、应用层不准重试 ;2、不能再次发送请求,也不重试;3、如果是致命的异常;

4、没有路由可以重试 也不重试。如果recover()返回的是true,那就会进入下一次循环,重新请求。

  回到主流程,注释5,请求没有成功,就释放资源,

注释6,如果请求成功了,Request followUp = followUpRequest(response, route);解析一下Response看是否需要重试或者重定向,需要就返回新的request。如果followUpRequest返回的Request为空,那边就表示不需要执行重试或者重定向,直接返回数据。如果followUp不为null,请求体不为空,但只需要请求一次时,那么就返回response。

在深入看一下followUpRequest ()方法。

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

        return null;

      default:
        return null;
    }
  }

主要根据响应码判断是否需要重定向,如果需要就取出重定向的URL并构建新的Request返回。

总结: RetryAndFollowUpInterceptor 拦截器主要用于连接失败重试和跟进处理重定向。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值