How to retry HTTP requests with OkHttp/Retrofit?

后端 未结 13 755
一向
一向 2020-12-07 09:04

I am using Retrofit/OkHttp (1.6) in my Android project.

I don\'t find any request retry mechanism built-in to either of them. On searching more, I read OkHttp seems

13条回答
  •  孤街浪徒
    2020-12-07 09:44

    Working prod solution.

    public int callAPI() {
        return 1; //some method to be retried
    }
    
    public int retrylogic()  throws InterruptedException, IOException{
        int retry = 0;
        int status = -1;
        boolean delay = false;
        do {
            if (delay) {
                Thread.sleep(2000);
            }
    
            try {
                status = callAPI();
            }
            catch (Exception e) {
                System.out.println("Error occured");
                status = -1;
            }
            finally {
                switch (status) {
                case 200:
                    System.out.println(" **OK**");
                    return status; 
                default:
                    System.out.println(" **unknown response code**.");
                    break;
                }
                retry++;
                System.out.println("Failed retry " + retry + "/" + 3);
                delay = true;
    
            } 
        }while (retry < 3);
    
        System.out.println("Aborting download of dataset.");
        return status;
    }
    

提交回复
热议问题