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和请求方式,这里就不详细讲解了。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
OkHttp是一个广泛使用的开源HTTP客户端库,用于在Android应用程序中进行网络通信。它提供了简单而强大的API,可以用于执行同步和异步的HTTP请求。在你提供的引用中,有关于OkHttp的三个方面的内容,我将分别进行解释。 首先,你需要创建一个OkHttpClient对象。这个对象是OkHttp库的核心,用于管理和执行HTTP请求。你可以使用以下代码来创建OkHttpClient对象: ```java OkHttpClient okHttpClient = new OkHttpClient(); ``` 其次,你需要在Android程序中进行网络请求时,使用异步处理的方式。在Android中,网络请求必须在单独的线程中执行,以避免阻塞主线程。你可以使用以下代码来执行异步的GET请求: ```java new Thread(() -> { Request request = new Request.Builder().url("https://www.httpbin.org/get?name=test&b=123").build(); try { Response response = okHttpClient.newCall(request).execute(); Log.d(TAG, "doGetSync: " + response.body().string()); } catch (IOException e) { e.printStackTrace(); } }).start(); ``` 同时,你需要在AndroidManifest.xml文件中添加网络请求权限。这样才能确保你的应用程序有权限进行网络通信。你可以在`<manifest>`标签下添加以下代码: ```xml <uses-permission android:name="android.permission.INTERNET"/> ``` 综上所述,你可以在Android应用程序中使用OkHttp库进行网络通信。首先,创建一个OkHttpClient对象;然后,使用异步的方式执行GET请求;最后,在AndroidManifest.xml文件中添加网络请求权限。 希望能对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值