(Android) OkHttp3.10 源码学习笔记 6 RetryAndFollowUpInterceptor分析

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

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

主要我们还是分析intercept方法

首先,它创建了一个StreamAllocation对象

StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
        createAddress(request.url()), call, eventListener, callStackTrace);
    this.streamAllocation = streamAllocation;

这个对象是用来建立http请求需要的网络组件的,从这个类名我们可以看出,是来分配stream的。虽然它是在这里创建的,但并未在这个拦截器中使用。

异常检测

下面进入了一个while(true)循环,通过proceed方法,去获取下一个拦截器的response。这边会捕获RouteException这个异常,下图我们可以看到这个异常会在哪些地方抛出


对抛出的异常代码里用recover方法进行了检测

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

看下面的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;
}
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;

响应码检测

158行,下面的代码是对响应码进行检测,能走到这,说明请求是成功的,但服务器返回不是200的情况,具体代码就不贴了,注释很详细

 Request followUp = followUpRequest(response, streamAllocation.route());

重试次数判断

再看169行

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

上面的代码对最大重试次数做了限制,通过阅读代码,我们知道这个数是20,如果超过了重试次数,便会释放连接。



Python网络爬虫与推荐算法新闻推荐平台:网络爬虫:通过Python实现新浪新闻的爬取,可爬取新闻页面上的标题、文本、图片、视频链接(保留排版) 推荐算法:权重衰减+标签推荐+区域推荐+热点推荐.zip项目工程资源经过严格测试可直接运行成功且功能正常的情况才上传,可轻松复刻,拿到资料包后可轻松复现出一样的项目,本人系统开发经验充足(全领域),有任何使用问题欢迎随时与我联系,我会及时为您解惑,提供帮助。 【资源内容】:包含完整源码+工程文件+说明(如有)等。答辩评审平均分达到96分,放心下载使用!可轻松复现,设计报告也可借鉴此项目,该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的。 【提供帮助】:有任何使用问题欢迎随时与我联系,我会及时解答解惑,提供帮助 【附带帮助】:若还需要相关开发工具、学习资料等,我会提供帮助,提供资料,鼓励学习进步 【项目价值】:可用在相关项目设计中,皆可应用在项目、毕业设计、课程设计、期末/期中/大作业、工程实训、大创等学科竞赛比赛、初期项目立项、学习/练手等方面,可借鉴此优质项目实现复刻,设计报告也可借鉴此项目,也可基于此项目来扩展开发出更多功能 下载后请首先打开README文件(如有),项目工程可直接复现复刻,如果基础还行,也可在此程序基础上进行修改,以实现其它功能。供开源学习/技术交流/学习参考,勿用于商业用途。质量优质,放心下载使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值