How to retry HTTP requests with OkHttp/Retrofit?

I don't know if this is an option for you but you could use RxJava together with Retrofit.

Retrofit is able to return Observables upon rest calls. On Oberservables you can just call retry(count) to resubscribe to the Observable when it emits an error.

You would have to define the call in your interface like this:

@GET("/data.json")
Observable<DataResponse> fetchSomeData();

Then you can subscribe to this Observable like this:

restApi.fetchSomeData()
.retry(5)  // Retry the call 5 times if it errors
.subscribeOn(Schedulers.io())  // execute the call asynchronously
.observeOn(AndroidSchedulers.mainThread())  // handle the results in the ui thread
.subscribe(onComplete, onError); 
// onComplete and onError are of type Action1<DataResponse>, Action1<Throwable>
// Here you can define what to do with the results

I had the same problem like you and this was actually my solution. RxJava is a really nice library to use in combination with Retrofit. You can even do many cool things in addition to retrying (like e.g. composing and chaining calls).


For Retrofit 2.x;

You can use Call.clone() method to clone request and execute it.

For Retrofit 1.x;

You can use Interceptors. Create a custom interceptor

    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.interceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            // try the request
            Response response = chain.proceed(request);

            int tryCount = 0;
            while (!response.isSuccessful() && tryCount < 3) {

                Log.d("intercept", "Request is not successful - " + tryCount);

                tryCount++;

                // retry the request
                response.close()
                response = chain.proceed(request);
            }

            // otherwise just pass the original response on
            return response;
        }
    });

And use it while creating RestAdapter.

new RestAdapter.Builder()
        .setEndpoint(API_URL)
        .setRequestInterceptor(requestInterceptor)
        .setClient(new OkClient(client))
        .build()
        .create(Adapter.class);