本文主要应用了OkHttp的Interceptor来实现自定义重试次数

虽然OkHttp自带retryOnConnectionFailure(true)方法可以实现重试,但是不支持自定义重试次数,所以有时并不能满足我们的需求。

#1.自定义重试拦截器:

/**
* 重试拦截器
*/
public class RetryIntercepter implements Interceptor { public int maxRetry;//最大重试次数
private int retryNum = 0;//假如设置为3次重试的话,则最大可能请求4次(默认1次+3次重试) public RetryIntercepter(int maxRetry) {
this.maxRetry = maxRetry;
} @Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
System.out.println("retryNum=" + retryNum);
Response response = chain.proceed(request);
while (!response.isSuccessful() && retryNum < maxRetry) {
retryNum++;
System.out.println("retryNum=" + retryNum);
response = chain.proceed(request);
}
return response;
}
}

#2.测试场景类:

 1 public class RetryTest {
2 String mUrl = "https://www.baidu.com/";
3 OkHttpClient mClient;
4
5 @Before
6 public void setUp() {
7 HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
8 logging.setLevel(HttpLoggingInterceptor.Level.BODY);
9
10 mClient = new OkHttpClient.Builder()
11 .addInterceptor(new RetryIntercepter(3))//重试
12 .addInterceptor(logging)//网络日志
13 .addInterceptor(new TestInterceptor())//模拟网络请求
14 .build();
15 }
16
17 @Test
18 public void testRequest() throws IOException {
19 Request request = new Request.Builder()
20 .url(mUrl)
21 .build();
22 Response response = mClient.newCall(request).execute();
23 System.out.println("onResponse:" + response.body().string());
24 }
25
26 class TestInterceptor implements Interceptor {
27
28 @Override
29 public Response intercept(Chain chain) throws IOException {
30 Request request = chain.request();
31 String url = request.url().toString();
32 System.out.println("url=" + url);
33 Response response = null;
34 if (url.equals(mUrl)) {
35 String responseString = "{\"message\":\"我是模拟的数据\"}";//模拟的错误的返回值
36 response = new Response.Builder()
37 .code(400)
38 .request(request)
39 .protocol(Protocol.HTTP_1_0)
40 .body(ResponseBody.create(MediaType.parse("application/json"), responseString.getBytes()))
41 .addHeader("content-type", "application/json")
42 .build();
43 } else {
44 response = chain.proceed(request);
45 }
46 return response;
47 }
48 }
49
50 }

#3.输出结果:

 1 retryNum=0
2 --> GET https://www.baidu.com/ HTTP/1.1
3 --> END GET
4 url=https://www.baidu.com/
5 <-- 400 null https://www.baidu.com/ (13ms)
6 content-type: application/json
7
8 {"message":"我是模拟的数据"}
9 <-- END HTTP (35-byte body)
10 retryNum=1
11 --> GET https://www.baidu.com/ HTTP/1.1
12 --> END GET
13 url=https://www.baidu.com/
14 <-- 400 null https://www.baidu.com/ (0ms)
15 content-type: application/json
16
17 {"message":"我是模拟的数据"}
18 <-- END HTTP (35-byte body)
19 retryNum=2
20 --> GET https://www.baidu.com/ HTTP/1.1
21 --> END GET
22 url=https://www.baidu.com/
23 <-- 400 null https://www.baidu.com/ (0ms)
24 content-type: application/json
25
26 {"message":"我是模拟的数据"}
27 <-- END HTTP (35-byte body)
28 retryNum=3
29 --> GET https://www.baidu.com/ HTTP/1.1
30 --> END GET
31 url=https://www.baidu.com/
32 <-- 400 null https://www.baidu.com/ (0ms)
33 content-type: application/json
34
35 {"message":"我是模拟的数据"}
36 <-- END HTTP (35-byte body)
37 onResponse:{"message":"我是模拟的数据"}

#4.结果分析:
>1. 这里我用一个TestInterceptor拦截器拦截掉真实的网络请求,实现response.code的自定义
2. 在RetryIntercepter中,通过response.isSuccessful()来对响应码进行判断,循环调用了多次chain.proceed(request)来实现重试拦截
3. 从输出中可以看到,一共请求了4次(默认1次+重试3次)。

#5.其它实现方式
如果你是使用OkHttp+Retrofit+RxJava,你也可以使用retryWhen操作符:retryWhen(new RetryWithDelay())来实现重试机制

 1 public class RetryWithDelay implements Func1<Observable<? extends Throwable>, Observable<?>> {
2
3 private final int maxRetries;
4 private final int retryDelayMillis;
5 private int retryCount;
6
7 public RetryWithDelay(int maxRetries, int retryDelayMillis) {
8 this.maxRetries = maxRetries;
9 this.retryDelayMillis = retryDelayMillis;
10 }
11
12 @Override
13 public Observable<?> call(Observable<? extends Throwable> attempts) {
14 return attempts
15 .flatMap(new Func1<Throwable, Observable<?>>() {
16 @Override
17 public Observable<?> call(Throwable throwable) {
18 if (++retryCount <= maxRetries) {
19 // When this Observable calls onNext, the original Observable will be retried (i.e. re-subscribed).
20 LogUtil.print("get error, it will try after " + retryDelayMillis + " millisecond, retry count " + retryCount);
21 return Observable.timer(retryDelayMillis,
22 TimeUnit.MILLISECONDS);
23 }
24 // Max retries hit. Just pass the error along.
25 return Observable.error(throwable);
26 }
27 });
28 }
29 }

OkHttp实现延时重试的更多相关文章

  1. RabbitMQ 发布订阅-实现延时重试队列(参考)

    RabbitMQ消息处理失败,我们会让失败消息进入重试队列等待执行,因为在重试队列距离真正执行还需要定义的时间间隔,因此,我们可以将重试队列设置成延时处理.今天参考网上其他人的实现,简单梳理下消息延时 ...

  2. RabbitMQ发布订阅实战-实现延时重试队列

    RabbitMQ是一款使用Erlang开发的开源消息队列.本文假设读者对RabbitMQ是什么已经有了基本的了解,如果你还不知道它是什么以及可以用来做什么,建议先从官网的 RabbitMQ Tutor ...

  3. [转]OkHttp使用完全教程

    1. 历史上Http请求库优缺点 在讲述OkHttp之前, 我们看下没有OkHttp的时代, 我们是如何完成http请求的.在没有OkHttp的日子, 我们使用HttpURLConnection或者H ...

  4. OKHttp 官方文档【一】

    最近工作比较忙,文章更新出现了延时.虽说写技术博客最初主要是写给自己,但随着文章越写越多,现在更多的是写给关注我技术文章的小伙伴们.最近一段时间没有更新文章,虽有工作生活孩子占用了大部分时间的原因,但 ...

  5. 简单的OkHttp使用介绍

    Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient.关于HttpURLConnection和HttpClient的选择>>官方博客尽管Go ...

  6. OkHttp使用教程

    Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient.关于HttpURLConnection和HttpClient的选择>>官方博客尽管Go ...

  7. OkHttp 3.4入门

    OkHttp 3.4入门 配置方法 (一)导入Jar包http://repo1.maven.org/maven2/com/squareup/okhttp3/okhttp/3.4.0-RC1/okhtt ...

  8. OkHttp:Java 平台上的新一代 HTTP 客户端

    OkHttp 简介 OkHttp 库的设计和实现的首要目标是高效.这也是选择 OkHttp 的重要理由之一.OkHttp 提供了对最新的 HTTP 协议版本 HTTP/2 和 SPDY 的支持,这使得 ...

  9. OkHttp使用进阶 译自OkHttp Github官方教程

    版权声明: 欢迎转载,但请保留文章原始出处 作者:GavinCT 出处:http://www.cnblogs.com/ct2011/p/3997368.html 没有使用过OkHttp的,可以先看Ok ...

  10. OkHttp使用全解析(转)。

    Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient.关于HttpURLConnection和HttpClient的选择>>官方博客尽管Go ...

随机推荐

  1. 有没有开发过⼀些vue插件?举例说说 - 批量引入插件

    有过,项⽬开发的时间⻓了,沉淀了不少业务通⽤全局组件,想把他们统⼀进⾏注册,就封装了⼀个⼩ 插件 当时其实⼀开始也没有什么思路,后来扒了⼀下 elementUI的源码,仿了⼀下它的写法,流程我还⼤概记 ...

  2. 背靠AI,让AI当牛马,解决程序员的烦恼

    开篇问题? 作为程序员的你,写代码累吗?累!苦嘛?苦,想哭嘛?哭不出来. 还在为工作中繁重的编码任务.复杂的调试过程以及不断更新的技术栈而苦恼吗?这些挑战不仅消耗大量的时间和精力,还时常让人陷入思维的 ...

  3. ARM 版 OpenEuler 22.03 部署 KubeSphere v3.4.0 不完全指南续篇

    作者:运维有术 前言 知识点 定级:入门级 KubeKey 安装部署 ARM 版 KubeSphere 和 Kubernetes ARM 版 KubeSphere 和 Kubernetes 常见问题 ...

  4. Nuget包本地调试以及自动打包上传

    项目过程中,经常需要打包Nuget包,并且引用本地Nuget包调试,完成后上传,因此做了点配置,分享给大家.如果大家有更好的方法欢迎分享. 1. 使用生成后事件自动打包 项目文件中本身是可以配置生成时 ...

  5. mysql主从复制详细部署

    1.异步复制:这是MySQL默认的复制模式.在这种模式下,主库在执行完客户端提交的事务后会立即将结果返回给客户端,并不关心从库是否已经接收并处理.这种模式的优点是实现简单,但缺点是如果主库崩溃,已经提 ...

  6. A星、Floyod、Bellman-Ford

    A 星算法 A 星和 Dijkstra 算法唯一区别在于堆中排序的依据.distance 数组仍然保存实际代价,预估代价只影响堆的弹出顺序. Dijkstra 根据源点到当前点的实际代价进行排序. A ...

  7. npm安装html2canvas依赖报错 npm ERR! Unexpected token < in JSON at position 0 while parsing near '<!DOCTYPE html> npm ERR! <htm...'

    今天安装某个依赖时发现npm ERR! 可我是正常操作啊,也没有升级啥的,咋就安装不了了? npm install --save html2canvas 报错信息如下: npm ERR! Unexpe ...

  8. 自动化构建镜像:Packer

    在介绍Packer之前,先来回顾一下未使用Packer时自定义虚拟机镜像的步骤.先在本地启动一个虚拟机,从安装系统开始,再进行自定义配置或应用安装,最后封装压缩成镜像,详细操作步骤可以参考我之前写的文 ...

  9. PbRL | Christiano 2017 年的开山之作,以及 Preference PPO / PrefPPO

    PrefPPO 首次(?)出现在 PEBBLE,作为 pebble 的一个 baseline,是用 PPO 复现 Christiano et al. (2017) 的 PbRL 算法. For eva ...

  10. 批量归一化(BN, Batch Normalization)

    现在的神经网络通常都特别深,在输出层向输入层传播导数的过程中,梯度很容易被激活函数或是权重以指数级的规模缩小或放大,从而产生"梯度消失"或"梯度爆炸"的现象,造 ...