How to retry HTTP requests with OkHttp/Retrofit?

后端 未结 13 747
一向
一向 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

    I am of the opinion that you shouldn't mix API handling (done by retrofit/okhttp) with retries. Retrying mechanisms are more orthogonal, and can be used in many other contexts as well. So I use Retrofit/OkHTTP for all the API calls and request/response handling, and introduce another layer above, for retrying the API call.

    In my limited Java experience so far, I have found jhlaterman's Failsafe library (github: jhalterman/failsafe) to be a very versatile library for handling many 'retry' situations cleanly. As an example, here's how I would use it with a retrofit instantiated mySimpleService, for authentication -

    AuthenticationResponse authResp = Failsafe.with(
    new RetryPolicy().retryOn(Arrays.asList(IOException.class, AssertionError.class))
            .withBackoff(30, 500, TimeUnit.MILLISECONDS)
            .withMaxRetries(3))
    .onRetry((error) -> logger.warn("Retrying after error: " + error.getMessage()))
    .get(() -> {
        AuthenticationResponse r = mySimpleAPIService.authenticate(
                new AuthenticationRequest(username,password))
                .execute()
                .body();
    
        assert r != null;
    
        return r;
    });
    

    The code above catches socket exceptions, connection errors, assertion failures, and retries on them maximum of 3 times, with exponential backoff. It also allows you to customise on-retry behaviour, and allows you to specify a fallback as well. It's quite configurable, and can adapt to most of the retry situations.

    Feel free to check the documentation of the library as it offers many other goodies apart from just retries.

提交回复
热议问题