OKHTTP拦截器RetryAndFollowUpInterceptor的简单分析

OKHTTP异步和同步请求简单分析
OKHTTP拦截器缓存策略CacheInterceptor的简单分析
OKHTTP拦截器ConnectInterceptor的简单分析
OKHTTP拦截器CallServerInterceptor的简单分析
OKHTTP拦截器BridgeInterceptor的简单分析
OKHTTP拦截器RetryAndFollowUpInterceptor的简单分析
OKHTTP结合官网示例分析两种自定义拦截器的区别

1、RetryAndFollowUpInterceptor的作用

看到该拦截器的名称就知道,它就是一个负责失败重连的拦截器,如果我们想要实现失败重连,那么就要在 OkHttpClient 进行配置,下面的代码片段是就是进行配置的。
不过呢,不是所有的网络请求失败了都可以进行重连的,因此呢,它内部会进行检测网络请求异常和响应码的情况,根据这些情况判断是否需要重新进行网络请求。

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.retryOnConnectionFailure();

RetryAndFollowUpInterceptor 是 OKHTTP 内置中的第一个拦截器,其功能主要有以下几点:

  • 1.创建 StreamAllocation 对象;
  • 2.调用 RealInterceptorChain.proceed(...)进行网络请求;
  • 3.根据异常结果或者响应结果判断是否要进行重新请求。

注意第二和第三点是在 while (true)内部执行的,也就是系统通过死循环来实现重连机制。下面阅读 OKHTTP 源码来看 RetryAndFollowUpInterceptor 内部是怎么实现以上 3 点功能的。

1.1、创建 StreamAllocation 对象

StreamAllocation 在 RetryAndFollowUpInterceptor 创建,它会在 ConnectInterceptor 中真正被使用到,主要就是用于获取连接服务端的 Connection 和用于进行跟服务端进行数据传输的输入输出流 HttpStream,具体的操作不是这篇博客的重点,只要了解它的作用的就行了。

1.2、网络请求

因为在 OKHTTP 中的拦截器的执行过程是一个递归的过程,也就是它内部会通过 RealInterceptorChain 这个类去负责将所有的拦截器进行串起来。只有所有的拦截器执行完毕之后,一个网络请求的响应 Response 才会被返回。

拦截器的执行过程.png

但是呢,在执行这个过程中,难免会出现一些问题,例如连接中断,握手失败或者服务器检测到未认证等,那么这个 resposne 的返回码就不是正常的 200 了,因此说这个 response 并不一定是可用的,或者说在请求过程就已经抛出异常了,例如超时异常等,那么 RetryAndFollowUpInterceptor 需要依据这些问题进行判断是否可以进行重新连接。

while(true){
    try{
        ...
        response = ((RealInterceptorChain) chain).proceed(request, 
        streamAllocation, null, null);
        ...
    }catch(RouteException e){
        //判断 RouteException  否可以重连
    }catch(IOException e){
        //判断 IOException 否可以重连
    }finally{
        //释放流
    }
    ...
}

1.3、 网络请求异常的“重连机制”

public Response proceed(Request request, StreamAllocation 
streamAllocation, HttpStream httpStream,Connection connection) throws IOException {

在上面已经介绍过了网络请求时通过 RealInterceptorChain#proceed 方法进行的,该方法的声明中抛出了 IOException ,表示在整个网络请求过程有可能出现 IOException,但是我们看了在 catch 中还有一个异常那就是 RouteException,下面是两个异常的继承结构:

  • IOException 它是编译时,需要在编译时期就要捕获或者抛出。
    public class IOException extends Exception

  • RouteException 是运行时异常,不需要显示的去捕获或者抛出。
    public final class RouteException extends RuntimeException


try {
  //网络请求
  response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
  //表示是否要释放连接,在 finally 中会使用到。
  releaseConnection = false;
} catch (RouteException e) {
  //路由异常RouteException 
  // 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;
  //重新进行while循环,进行网络请求
  continue;
} catch (IOException e) {
   //检测该IO异常是否能重新连接
  // An attempt to communicate with a server failed. The request may have been sent.
  if (!recover(e, false, request)) throw e;
  //可以重新连接,那么就不要释放连接
  releaseConnection = false;
 //重新进行while循环,进行网络请求
  continue;
} finally {
  //当 releaseConnection 为true时表示需要释放连接了。
  // We're throwing an unchecked exception. Release any resources.
  if (releaseConnection) {
    streamAllocation.streamFailed(null);
    streamAllocation.release();
  }

1.3.1、RouteException 异常的重连机制

在 RouteException 的重连机制主要做了这样几件事:

  • 通过 recover 方法检测该 RouteException 是否能重新连接;
  • 可以重新连接,那么就不要释放连接 releaseConnection = false;
  • continue进入下一次循环,进行网络请求;
  • 不可以重新连接就直接走 finally 代码块释放连接。

下面是通过 find Usages 得到 RouteException 被哪里抛出的图,从图可以看出 RouteException 是在获取一个 HttpStream 流和与 SOCKET 建立连接时出现异常才被抛出的,在抛异常的方法内部并没有显示地去捕获,因此异常会被 RetryAndFollowUpInterceptor#intercept 中的 catch 捕获,下面就是对捕获的异常的处理。

RouteException的抛出.png

查看源码可以知道 RouteException 和 IOException 异常检测都会调用 recover 方法进行判断,主要是第二个参数不一样,这里传入的是true,表示该异常是 RouteException ,下面 IOException 检测时传入的参数时 false 。

if (!recover(e.getLastConnectException(), true, request)) throw 
e.getLastConnectException();

1.3.2、 recover 方法异常检测

private boolean recover(IOException e, boolean routeException, Request userRequest) {
  streamAllocation.streamFailed(e);
  //1.判断 OkHttpClient 是否支持失败重连的机制
  // The application layer has forbidden retries.
  if (!client.retryOnConnectionFailure()) return false;
  // 在该方法中传入的 routeException值 为 true
  // We can't send the request body again.
  if (!routeException && userRequest.body() instanceof UnrepeatableRequestBody) return false;
  //2.isRecoverable 检测该异常是否是致命的。
  // This exception is fatal.
  if (!isRecoverable(e, routeException)) return false;
  // No more routes to attempt.
  //3.是否有更多的路线
  if (!streamAllocation.hasMoreRoutes()) return false;
  // For failure recovery, use the same route selector with a new connection.
  return true;
}

从上面源码可以看出 recover 方法主要做了以下几件事:

  • 1.判断 OkHttpClient 是否支持失败重连的机制;
    • 如果不支持重连,就表示请求失败就失败了,不能再重试了。
  • 2.通过 isRecoverable 方法检测该异常是否是致命的;
  • 3.是否有更多的路线,可以重试。

1.3.3、isRecoverable 方法异常检测

在该方法中会检测异常是否为严重异常,严重异常就不要进行重连了,下面检测的异常都做了注释。这里涉及到一个
SocketTimeoutException 的异常,表示连接超时异常,这个异常还是可以进行重连的,也就是说** OKHTTP 内部在连接超时时是会自动进行重连的。**

private boolean isRecoverable(IOException e, boolean routeException) {
  //ProtocolException 这种异常属于严重异常,不能进行重新连接
  // 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.3.4、IOException 异常的重连机制

IOException 异常的检测实际上和 RouteException 是一样的,只是传入 recover 方法的第二个参数为 false 而已,表示该异常不是 RouteException ,这里就不分析了。

// An attempt to communicate with a server failed. The request may 
//have been sent.
if (!recover(e, false, request)) throw e;

1.4、followUpRequest 响应码检测

当代码可以执行到 followUpRequest 方法就表示这个请求是成功的,但是服务器返回的状态码可能不是 200 ok 的情况,这时还需要对该请求进行检测,其主要就是通过返回码进行判断的。

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;
      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;
      // Redirects don't include a request body.
      Request.Builder requestBuilder = userResponse.request().newBuilder();
      if (HttpMethod.permitsRequestBody(method)) {
        if (HttpMethod.redirectsToGet(method)) {
          requestBuilder.method("GET", null);
        } else {
          requestBuilder.method(method, null);
        }
        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");
      }
      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 (userResponse.request().body() instanceof UnrepeatableRequestBody) {
        return null;
      }
      return userResponse.request();
    default:
      return null;
  }
}

下面是服务器返回的状态码的判断,对于这些状态我都没遇到过,在这里只是将其列举出来而已。

  • 407 HTTP_PROXY_AUTH 表示需要经过代理服务器认证;

  • 401 HTTP_UNAUTHORIZED 身份未认证;

  • 307HTTP_TEMP_REDIRECT 308HTTP_PERM_REDIRECT 重定向(只有是 GET 和 HEAD)才可以;

  • 300HTTP_MULT_CHOICE 301HTTP_MOVED_PERM ;

  • 302 HTTP_MOVED_TEMP 303HTTP_SEE_OTHER 通过client.followRedirects()判断是否运行重定向,之后获取响应头 Location 值,这就是要重定向的地址;

  • HTTP_CLIENT_TIMEOUT 客户端超时的情况。

1.5、重试次数判断

在 RetryAndFollowUpInterceptor 内部有一个 MAX_FOLLOW_UPS 常量,它表示该请求可以重试多少次,在 OKHTTP 内部中是不能超过 20 次,如果超过 20 次,那么就不会再请求了。

private static final int MAX_FOLLOW_UPS = 20;

if (++followUpCount > MAX_FOLLOW_UPS) {
  streamAllocation.release();
  throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容