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

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

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

/**
* 重试拦截器
*/
public class RetryIntercepter implements Interceptor { public int maxRetry;//最大重试次数
private int retryNum = ;//假如设置为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.测试场景类:

 public class RetryTest {
String mUrl = "https://www.baidu.com/";
OkHttpClient mClient; @Before
public void setUp() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY); mClient = new OkHttpClient.Builder()
.addInterceptor(new RetryIntercepter())//重试
.addInterceptor(logging)//网络日志
.addInterceptor(new TestInterceptor())//模拟网络请求
.build();
} @Test
public void testRequest() throws IOException {
Request request = new Request.Builder()
.url(mUrl)
.build();
Response response = mClient.newCall(request).execute();
System.out.println("onResponse:" + response.body().string());
} class TestInterceptor implements Interceptor { @Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
String url = request.url().toString();
System.out.println("url=" + url);
Response response = null;
if (url.equals(mUrl)) {
String responseString = "{\"message\":\"我是模拟的数据\"}";//模拟的错误的返回值
response = new Response.Builder()
.code()
.request(request)
.protocol(Protocol.HTTP_1_0)
.body(ResponseBody.create(MediaType.parse("application/json"), responseString.getBytes()))
.addHeader("content-type", "application/json")
.build();
} else {
response = chain.proceed(request);
}
return response;
}
} }

#3.输出结果:

 retryNum=
--> GET https://www.baidu.com/ HTTP/1.1
--> END GET
url=https://www.baidu.com/
<-- null https://www.baidu.com/ (13ms)
content-type: application/json {"message":"我是模拟的数据"}
<-- END HTTP (-byte body)
retryNum=
--> GET https://www.baidu.com/ HTTP/1.1
--> END GET
url=https://www.baidu.com/
<-- null https://www.baidu.com/ (0ms)
content-type: application/json {"message":"我是模拟的数据"}
<-- END HTTP (-byte body)
retryNum=
--> GET https://www.baidu.com/ HTTP/1.1
--> END GET
url=https://www.baidu.com/
<-- null https://www.baidu.com/ (0ms)
content-type: application/json {"message":"我是模拟的数据"}
<-- END HTTP (-byte body)
retryNum=
--> GET https://www.baidu.com/ HTTP/1.1
--> END GET
url=https://www.baidu.com/
<-- null https://www.baidu.com/ (0ms)
content-type: application/json {"message":"我是模拟的数据"}
<-- END HTTP (-byte body)
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())来实现重试机制

 public class RetryWithDelay implements Func1<Observable<? extends Throwable>, Observable<?>> {

         private final int maxRetries;
private final int retryDelayMillis;
private int retryCount; public RetryWithDelay(int maxRetries, int retryDelayMillis) {
this.maxRetries = maxRetries;
this.retryDelayMillis = retryDelayMillis;
} @Override
public Observable<?> call(Observable<? extends Throwable> attempts) {
return attempts
.flatMap(new Func1<Throwable, Observable<?>>() {
@Override
public Observable<?> call(Throwable throwable) {
if (++retryCount <= maxRetries) {
// When this Observable calls onNext, the original Observable will be retried (i.e. re-subscribed).
LogUtil.print("get error, it will try after " + retryDelayMillis + " millisecond, retry count " + retryCount);
return Observable.timer(retryDelayMillis,
TimeUnit.MILLISECONDS);
}
// Max retries hit. Just pass the error along.
return Observable.error(throwable);
}
});
}
}

最新文章

  1. 动手做第一个Chrome插件
  2. jQuery遮罩层登录对话框
  3. 使用flex布局通过order控制显示顺序
  4. Redis 3.2 Linux 环境集群搭建与java操作
  5. HDU 1251统计难题
  6. supersr--打电话/短信分享/邮件分享
  7. tomcat 设置根目录访问
  8. c与c++中的extern const的区别和联系
  9. wp8 入门到精通 LINQ to SQL
  10. org.unsaved transient instance - save the transient instance before flushing: bug解决方案
  11. 【开源项目10】安卓图表引擎AChartEngine
  12. 学习PHP爬虫--《Webbots、Spiders和Screen Scrapers:技术解析与应用实践(原书第2版)》
  13. TCP回射服务器程序:str_echo函数
  14. MySQL 事物
  15. 201521123037 《Java程序设计》第5周学习总结
  16. MyBatis_关联关系查询
  17. JVM学习(一)
  18. java web项目最简单的结构
  19. CListCtrl颜色设置
  20. problem:vue组件局部刷新,在组件销毁(destroyed)时取消刷新无效问题

热门文章

  1. [UWP]如何使用Fluent Design System (下)
  2. CentOS配置SSH免密登录
  3. V4l2的结构体 --- ioctl【转】
  4. 如何给网站添加SSL证书(免费)
  5. RabbitMQ 学习开发笔记
  6. BZOJ:1443: [JSOI2009]游戏Game
  7. kali中的webshell
  8. [国嵌攻略][149][Yaffs2文件系统应用]
  9. Spark算子--map和flatMap
  10. Windows7下远程操作虚拟机