Java tutorial
/* * Copyright 2016 Heroic Labs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.heroiclabs.sdk.android.util.http; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import java.io.IOException; import java.net.HttpURLConnection; import java.util.Random; import lombok.RequiredArgsConstructor; /** * An OkHttp interceptor that retries calls in case of network failures. */ @RequiredArgsConstructor(suppressConstructorProperties = true) public class RetryInterceptor implements Interceptor { /** Generator used to randomise delay between request attempts. */ private final Random random = new Random(); /** A maximum number of attempts. */ private final int maxAttempts; /** {@inheritDoc} */ @Override public Response intercept(final Chain chain) throws IOException { return attemptRequest(chain, 1); } /** * Recursive helper method that catches IOExceptions and calls itself again if the maximum number of allowed * retries has not yet been exceeded. * * @param chain The request chain. * @param count The number of the current attempt. * @return The response forwarded by the chain. * @throws IOException if even after all retries the request fails. */ private Response attemptRequest(final Chain chain, final int count) throws IOException { try { final Request request = chain.request(); final Response response = chain.proceed(request); // Treat blank 504 responses as network issues. if (response.code() == HttpURLConnection.HTTP_GATEWAY_TIMEOUT && response.body().contentLength() == 0l) { throw new IOException("Unexpected 504 responses status"); } return response; } catch (final IOException e) { if (count < maxAttempts) { try { // Wait between 100 and 200 milliseconds, inclusive. Thread.sleep(random.nextInt(101) + 100); } catch (final InterruptedException ex) { // Don't care. } return attemptRequest(chain, count + 1); } else { throw e; } } } }