OkHttp自定義重試次數

来源:https://www.cnblogs.com/ganchuanpu/archive/2018/02/01/8399681.html
-Advertisement-
Play Games

本文主要應用了OkHttp的Interceptor來實現自定義重試次數 雖然OkHttp自帶retryOnConnectionFailure(true)方法可以實現重試,但是不支持自定義重試次數,所以有時並不能滿足我們的需求。 #1.自定義重試攔截器: #2.測試場景類: #3.輸出結果: #4.結 ...


本文主要應用了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 }

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一、問題現象 20180201:15:06:25:028653 gpinitsystem:sdw1-2:gpadmin-[INFO]: 20180201:15:06:25:028653 gpinitsystem:sdw1-2:gpadmin-[INFO]:-Greenplum Primary Seg ...
  • 準備 1、三台虛擬機 192.168.1.128 Nimbus 192.168.1.131 Supervisor 192.168.1.132 Supervisor 2、JDK1.8 3、Zookeeper3.4.10 4、Storm-1.1.1 步驟 1、配置Storm(PS:三台機器的配置都是這樣 ...
  • --用INSERT插入單行數據 在SQL中,可以通過INSERT...VALUES語句直接向資料庫表中插入數據。可以整行,也可以部分列。 基本語法: INSERT INTO table_name [column1,column2...] VALUES (values1,values2...) 如果t ...
  • LSQL Developer作為強大的Oracle編輯工具,卻只支持32bit,本文提供在安裝用LSQL Developer打開64bitOracle的操作方法 工具/原料 oracle11g安裝包(64位) oracle11g客戶端(32位) LSQL Developer安裝包 oracle11g ...
  • hadoop集群有三種運行模式:單機模式、偽分佈模式、完全分佈模式。我們這裡搭建第三種完全分佈模式,即使用分散式系統,在多個節點上運行。 1 環境準備 1.1 配置DNS 進入配置文件,添加主節點和從節點的ip映射關係: 1.2 關閉防火牆 1.3 配置免密碼登錄 (1)每個節點都首先進入/root ...
  • 一、創建用戶 二、下載軟體包並解壓 三、安裝所需包組 四、建立資料庫目錄並設置屬主屬組 五、編譯安裝 cmake . \-DCMAKE_INSTALL_PREFIX=/app/mysql \-DMYSQL_DATADIR=/mysqldb/ \-DSYSCONFDIR=/etc \-DMYSQL_U ...
  • 個人開發者與企業開發者的一個主要的區別在於獨立開發者授權描述文件必須列出具體的設備。另一個不同就是開發者賬戶最多使用100台設備,而企業則可以讓蘋果公司生成未鎖定到特定設備並可以安裝到任何設備上的授權描述文件。 參考資料:《黑客攻防技術寶典-iOS實戰篇》 ...
  • 首先,先貼上樣本代碼 使用說明: 一、在AndroidManiFest文件中添加存儲卡許可權 二、通過findviewbyid找到Button或者是imageButton,並綁定監聽事件 三、複製上述的樣本代碼放在onClick事件下麵,同時,添加一個全局靜態變數 四、在button或者是imageB ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...