okhttp之RetryAndFollowUpInterceptor

RetryAndFollowUpInterceptor是okhttp自己的第一个拦截器,这个拦截器主要负责请求的重定向和重试。下面看代码:
先来分析重试部分的代码

@Override public Response intercept(Chain chain) throws  IOException {
Request request = chain.request();

//创建StreamAllocation,在后面的拦截器中用到
streamAllocation = new StreamAllocation(
    client.connectionPool(), createAddress(request.url()), callStackTrace);

int followUpCount = 0;
Response priorResponse = null;
while (true) {
  if (canceled) {
    streamAllocation.release();
    throw new IOException("Canceled");
  }

  Response response = null;
  boolean releaseConnection = true;
  try {
    response = ((RealInterceptorChain) chain).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.
    //是否需要重新请求
    if (!recover(e.getLastConnectException(), true, request)) throw e.getLastConnectException();
    releaseConnection = false;
    continue;
  } catch (IOException e) {
    // An attempt to communicate with a server failed. The request may have been sent.
    //如果是IO异常,判断是否需要重试
    if (!recover(e, false, request)) throw e;
    releaseConnection = false;
    continue;
  } finally {
    // We're throwing an unchecked exception. Release any resources.
    //如果发生了异常,并且需要重试的情况下,releaseConnection为false,不会执行这个操作,否则,不需要再进行重试请求了,此时可以释放连接了
    if (releaseConnection) {
    //释放掉连接
      streamAllocation.streamFailed(null);
      streamAllocation.release();
    }
  }

可以看出,在请求发生了RouteException 或者IOException时,经过recover()方法判断,如果符合重试的条件,就不继续往下执行而是continue在while循环中执行下一次请求(也就是重试)。那么什么情况下需要重试呢?这就需要看recover方法里面具体怎么操作的了。

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

// The application layer has forbidden retries.
//应用层是否允许进行重试(用户可以自己配置)
if (!client.retryOnConnectionFailure()) return false;

// We can't send the request body again.
//如果是routeException,并且请求体属于不可重复请求的
if (!routeException && userRequest.body() instanceof UnrepeatableRequestBody) return false;

// This exception is fatal.
if (!isRecoverable(e, routeException)) return false;

// No more routes to attempt.
//是否还有其他路由(这里也说明了  如果一直发生routeException的情况,还需要查看是否有路由,并不会无限的循环下去)
if (!streamAllocation.hasMoreRoutes()) return false;

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

不可以进行重试的异常一共有四种:
1、在调用okhttp请求的时候,设置为不可重试
2、不属于路由异常(即连接成功了),但是请求体属于不可重复的请求
3、!isRecoverable(e, routeException),这里调用了isRecoverable()方法来判断。isRecoverable方法的代码如下:

private boolean isRecoverable(IOException e, boolean routeException) {
// 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 && routeException;
}

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

这里面判断了在连接过程中发生的情况:
1)属于ProtocolException异常的情况,不进行重连
2)属于中断异常(如果是socket连接超时除外)不进行重连
3)证书导致的异常不进行重连
4)访问网站的证书不在你可以信任的证书列表中 不进行重连

4、是否还有其他路由来进行重试。由于每次重试都要切换一个路由,当没有更多的路由时,就不进行重试了。
关于判断是否重试的代码就到这里结束了。下面开始看关于重定向的代码:

//省略上面重试的代码
  ......
 //获取重定向的请求
  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());
  }

  //如果请求的地址发生了变化,重新创建streamAllocation
  if (!sameConnection(response, followUp.url())) {
    streamAllocation.release();
    streamAllocation = new StreamAllocation(
        client.connectionPool(), createAddress(followUp.url()), callStackTrace);
  } else if (streamAllocation.codec() != null) {
    throw new IllegalStateException("Closing the body of " + response
        + " didn't close its backing stream. Bad interceptor?");
  }

  request = followUp;
  priorResponse = response;
}

要进行重定向首先需要根据上次的response获取到重定向的请求,这一步是在followUpRequest(response)方法中实现的,这个方法后面再进行分析。先看获取到重定向请求后做了什么操作。
一、判断followUp (根据上次请求返回的response获取到的重定向请求)是否为空,如果为空,说明不需要重定向,那么直接返回response,就不往下执行第二步了。
二、到这一步,说明需要执行重定向请求。那么判断已经执行的重定向请求的次数是否大于一定的数量,如果大于,抛出异常,否则继续往下执行
三、如果followUp.body() instanceof UnrepeatableRequestBody,说明不希望这个请求重复进行提交,那么也抛出异常,不往下执行了
四、到了这一步,基本上就可以进行重定向了。判断要重定向的地址是否和之前的地址相同,如果不同需要重新进行新的连接。执行完这一步,就可以循环开始下一次的请求了
接下来看一下是如何根据response获取重定向的请求的,这就要看Request followUp = followUpRequest(response)这个方法了。这里面生成的request主要是根据返回的状态吗code和请求方式,这里就不详细讲解了。

本篇文章感觉写的并不是很清楚透彻,大概是因为对代码的理解还不是很到位,就当做是学习笔记了。有写的不对的地方,欢迎批评指正。

    原文作者:黑猫警长_01
    原文地址: https://www.jianshu.com/p/b4805388fb87
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞