/* * Copyright 2014-2015 GameUp * * 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 io.gameup.android.http; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.Response; import java.io.IOException; /** * An OkHttp interceptor that retries calls in case of network failures. */ public class RetryInterceptor implements Interceptor { /** A fixed maximum number of connection attempts. */ public static final int MAX_ATTEMPTS = 3; /** {@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 { return chain.proceed(chain.request()); } catch (final IOException e) { if (count < MAX_ATTEMPTS) { return attemptRequest(chain, count + 1); } else { throw e; } } } }