87

我在我的 Android 项目中使用 Retrofit/OkHttp (1.6)。

我没有找到任何内置的请求重试机制。在搜索更多时,我读到 OkHttp 似乎有静默重试。我没有看到在我的任何连接(HTTP 或 HTTPS)上发生这种情况。如何使用 okclient 配置重试?

现在,我正在捕获异常并重试维护计数器变量。

4

15 回答 15

95

对于改造 2.x;

您可以使用Call.clone()方法克隆请求并执行它。

对于改造 1.x;

您可以使用拦截器。创建自定义拦截器

    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 = chain.proceed(request);
            }

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

并在创建 RestAdapter 时使用它。

new RestAdapter.Builder()
        .setEndpoint(API_URL)
        .setRequestInterceptor(requestInterceptor)
        .setClient(new OkClient(client))
        .build()
        .create(Adapter.class);
于 2015-07-30T20:41:35.897 回答
46

我不知道这是否适合您,但您可以将RxJava与 Retrofit 一起使用。

Retrofit 能够在休息调用时返回 Observables。retry(count)在 Observables 上,您可以在 Observable 发出错误时调用以重新订阅它。

您必须像这样在界面中定义调用:

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

然后你可以像这样订阅这个 Observable:

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

我和你有同样的问题,这实际上是我的解决方案。RxJava 是一个非常好的库,可以与 Retrofit 结合使用。除了重试之外,您甚至可以做许多很酷的事情(例如编写和链接调用)。

于 2014-07-11T07:57:41.017 回答
22

我认为您不应该将 API 处理(由改造/okhttp 完成)与重试混合使用。重试机制更加正交,也可以在许多其他情况下使用。所以我使用 Retrofit/OkHTTP 来处理所有的 API 调用和请求/响应处理,并在上面引入另一个层,用于重试 API 调用。

到目前为止,在我有限的 Java 经验中,我发现 jhlaterman 的 Failsafe 库(github:jhalterman/failsafe)是一个非常通用的库,可以干净地处理许多“重试”情况。例如,这是我将如何将它与实例化 mySimpleService 的改造一起用于身份验证 -

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;
});

上面的代码捕获套接字异常、连接错误、断言失败,并在它们上重试最多 3 次,具有指数退避。它还允许您自定义重试行为,并允许您指定回退。它的可配置性很强,可以适应大多数重试情况。

随意查看该库的文档,因为它除了重试之外还提供了许多其他好东西。

于 2018-11-19T03:55:17.180 回答
13

response.isSuccessful() 的问题是当您遇到像 SocketTimeoutException 这样的异常时。

我修改了原始代码来修复它。

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();
        Response response = null;
        boolean responseOK = false;
        int tryCount = 0;

        while (!responseOK && tryCount < 3) {
            try {
                 response = chain.proceed(request);
                 responseOK = response.isSuccessful();                  
            }catch (Exception e){
                 Log.d("intercept", "Request is not successful - " + tryCount);                     
            }finally{
                 tryCount++;      
            }
        }

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

希望能帮助到你。问候。

于 2015-12-21T20:51:30.483 回答
4

感谢最佳答案,这对我有用。如果存在连接问题,最好等待几秒钟再重试。

public class ErrorInterceptor implements Interceptor {
ICacheManager cacheManager;
Response response = null;
int tryCount = 0;
int maxLimit = 3;
int waitThreshold = 5000;
@Inject
public ErrorInterceptor() {

}

@Override
public Response intercept(Chain chain){

   // String language =  cacheManager.readPreference(PreferenceKeys.LANGUAGE_CODE);
  Request request = chain.request();
  response =  sendReqeust(chain,request);
    while (response ==null && tryCount < maxLimit) {
        Log.d("intercept", "Request failed - " + tryCount);
        tryCount++;
        try {
            Thread.sleep(waitThreshold); // force wait the network thread for 5 seconds
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
       response = sendReqeust(chain,request);
    }
    return response;
}

private Response sendReqeust(Chain chain, Request request){
    try {
        response = chain.proceed(request);
        if(!response.isSuccessful())
            return null;
        else
        return response;
    } catch (IOException e) {
      return null;
    }
}

}

于 2017-05-03T03:41:36.420 回答
3

在 OkHttp 3.9.1 上对我有用的解决方案(考虑这个问题的其他答案):

@NonNull
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
    Request  request      = chain.request();
    int      retriesCount = 0;
    Response response     = null;

    do {
        try {
            response = chain.proceed(request);

        // Retry if no internet connection.
        } catch (ConnectException e) {
            Log.e(TAG, "intercept: ", e);
            retriesCount++;

            try {
                Thread.sleep(RETRY_TIME);

            } catch (InterruptedException e1) {
                Log.e(TAG, "intercept: ", e1);
            }
        }

    } while (response == null && retriesCount < MAX_RETRIES);

    // If there was no internet connection, then response will be null.
    // Need to initialize response anyway to avoid NullPointerException.
    if (response == null) {
        response = chain.proceed(newRequest);
    }

    return response;
}
于 2019-04-29T13:37:21.060 回答
2

我发现Sinan Kozak提供的方式(OKHttpClient拦截器)在http连接失败时不起作用,还没有关注HTTP响应。

所以我用另一种方法来挂钩 Observable 对象,在它上面调用 .retryWhen 。另外,我添加了 retryCount 限制。

import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.HttpException;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.jackson.JacksonConverterFactory;
import rx.Observable;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

然后

    RxJavaCallAdapterFactory originCallAdaptorFactory = RxJavaCallAdapterFactory.create();

    CallAdapter.Factory newCallAdaptorFactory = new CallAdapter.Factory() {
        @Override
        public CallAdapter<?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {

            CallAdapter<?> ca = originCallAdaptorFactory.get(returnType, annotations, retrofit);

            return new CallAdapter<Observable<?>>() {

                @Override
                public Type responseType() {
                    return ca.responseType();
                }

                int restRetryCount = 3;

                @Override
                public <R> Observable<?> adapt(Call<R> call) {
                    Observable<?> rx = (Observable<?>) ca.adapt(call);

                    return rx.retryWhen(errors -> errors.flatMap(error -> {
                        boolean needRetry = false;
                        if (restRetryCount >= 1) {
                            if (error instanceof IOException) {
                                needRetry = true;
                            } else if (error instanceof HttpException) {
                                if (((HttpException) error).code() != 200) {
                                    needRetry = true;
                                }
                            }
                        }

                        if (needRetry) {
                            restRetryCount--;
                            return Observable.just(null);
                        } else {
                            return Observable.error(error);
                        }
                    }));
                }
            };
        }
    };                

然后添加或替换

.addCallAdapterFactory(RxJavaCallAdapterFactory.create())

.addCallAdapterFactory(newCallAdaptorFactory)

例如:

return new Retrofit
        .Builder()
        .baseUrl(baseUrl)
        .client(okClient)
        .addCallAdapterFactory(newCallAdaptorFactory)
        .addConverterFactory(JacksonConverterFactory.create(objectMapper));

注意:为简单起见,我只是将HTTP代码> 404代码视为重试,请自行修改。

另外,如果http响应是200,那么上面rx.retryWhen不会被调用,如果你坚持要检查这样的响应,你可以rx.subscribeOn(...throw error...在.retryWhen之前添加。

于 2016-06-30T07:43:11.750 回答
2

对于那些更喜欢拦截器来处理重试问题的人 - 基于 Sinan 的回答,这是我提出的拦截器,它包括重试计数和退避延迟,并且仅在网络可用且请求不可用时重试尝试取消。(仅处理 IOExceptions(SocketTimeout、UnknownHost 等))

    builder.addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            // try the request
            Response response = null;
            int tryCount = 1;
            while (tryCount <= MAX_TRY_COUNT) {
                try {
                    response = chain.proceed(request);
                    break;
                } catch (Exception e) {
                    if (!NetworkUtils.isNetworkAvailable()) {
                        // if no internet, dont bother retrying request
                        throw e;
                    }
                    if ("Canceled".equalsIgnoreCase(e.getMessage())) {
                        // Request canceled, do not retry
                        throw e;
                    }
                    if (tryCount >= MAX_TRY_COUNT) {
                        // max retry count reached, giving up
                        throw e;
                    }

                    try {
                        // sleep delay * try count (e.g. 1st retry after 3000ms, 2nd after 6000ms, etc.)
                        Thread.sleep(RETRY_BACKOFF_DELAY * tryCount);
                    } catch (InterruptedException e1) {
                        throw new RuntimeException(e1);
                    }
                    tryCount++;
                }
            }

            // otherwise just pass the original response on
            return response;
        }
    });
于 2016-08-06T12:29:42.350 回答
1

只想分享我的版本。它使用 rxJava retryWhen 方法。我的版本每 N=15 秒重试一次连接,当互联网连接恢复时几乎立即发出重试。

public class RetryWithDelayOrInternet implements Function<Flowable<? extends Throwable>, Flowable<?>> {
public static boolean isInternetUp;
private int retryCount;

@Override
public Flowable<?> apply(final Flowable<? extends Throwable> attempts) {
    return Flowable.fromPublisher(s -> {
        while (true) {
            retryCount++;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                attempts.subscribe(s);
                break;
            }
            if (isInternetUp || retryCount == 15) {
                retryCount = 0;
                s.onNext(new Object());
            }
        }
    })
            .subscribeOn(Schedulers.single());
}}

你应该在 .subscribe 之前使用它,如下所示:

.retryWhen(new RetryWithDelayOrInternet())

您应该手动更改 isInternetUp 字段

public class InternetConnectionReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
    boolean networkAvailable = isNetworkAvailable(context);
    RetryWithDelayOrInternet.isInternetUp = networkAvailable;
}
public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}}
于 2018-02-14T13:59:58.627 回答
0

它似乎将出现在 API 规范的改造 2.0 中: https ://github.com/square/retrofit/issues/297 。目前,最好的方法似乎是捕获异常并手动重试。

于 2014-10-22T21:04:01.653 回答
0

文档中所述,更好的方法可能是使用烘焙的身份验证器,例如: private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    client.setAuthenticator(new Authenticator() {
      @Override public Request authenticate(Proxy proxy, Response response) {
        System.out.println("Authenticating for response: " + response);
        System.out.println("Challenges: " + response.challenges());
        String credential = Credentials.basic("jesse", "password1");
        return response.request().newBuilder()
            .header("Authorization", credential)
            .build();
      }

      @Override public Request authenticateProxy(Proxy proxy, Response response) {
        return null; // Null indicates no attempt to authenticate.
      }
    });

    Request request = new Request.Builder()
        .url("http://publicobject.com/secrets/hellosecret.txt")
        .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
  }
于 2015-12-11T00:38:35.390 回答
0

我在这个问题上玩了很多,试图找到重试改造请求的最佳方法。我正在使用 Retrofit 2,所以我的解决方案适用于 Retrofit 2。对于 Retrofit 1,您必须像此处接受的答案一样使用拦截器。@joluet 的答案是正确的,但他没有提到 retry 方法需要在 .subscribe(onComplete, onError) 方法之前调用。这非常重要,否则不会像@joluet 回答中提到的@pocmo 那样再次重试请求。这是我的例子:

final Observable<List<NewsDatum>> newsDetailsObservable = apiService.getCandidateNewsItem(newsId).map((newsDetailsParseObject) -> {
                    return newsDetailsParseObject;
                });

newsDetailsObservable.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .retry((integer, throwable) -> {
                //MAX_NUMBER_TRY is your maximum try number
                if(integer <= MAX_NUMBER_TRY){
                    return true;//this will retry the observable (request)
                }
                return false;//this will not retry and it will go inside onError method
            })
            .subscribe(new Subscriber<List<NewsDatum>>() {
                @Override
                public void onCompleted() {
                    // do nothing
                }

                @Override
                public void onError(Throwable e) {
                   //do something with the error
                }

                @Override
                public void onNext(List<NewsDatum> apiNewsDatum) {
                    //do something with the parsed data
                }
            });

apiService 是我的 RetrofitServiceProvider 对象。

顺便说一句:我使用的是 Java 8,所以代码中有很多 lambda 表达式。

于 2016-07-31T22:24:25.210 回答
0

工作产品解决方案。

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;
}
于 2019-08-01T14:58:52.717 回答
0

正如之前的用户所说,如果您使用的是 Retrofit2 call.clone 就足够了,但我还想添加一个简单的示例来说明它的外观:

public class CallbackImpl implements Callback<ResponseBody> {
    private final Set<Integer> retryCode = new HashSet<>(Arrays.asList(503, 504));
    int requestRetry  = 1;

    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        if (response.code() == 201) {
            // Object was created.
        } else {
            if (requestRetry != 0 && retryCode.contains(response.code())) {
                call.clone().enqueue(this);
            } else {
                // Handle the error
            }
        }
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable throwable) {
        if (throwable instanceof IOException) {
            // Network failure
        } else {
            // Conversion Issue
        }
    }
}
于 2021-06-21T23:34:57.610 回答
0

Failsafe 3.2.2 有一个OkHttp 模块,这使得这很容易:

Call call = client.newCall(request);
RetryPolicy<Response> retryPolicy = RetryPolicy.ofDefaults();
FailsafeCall failsafeCall = FailsafeCall.with(retryPolicy).compose(call);

// Execute with retries
Response response = failsafeCall.execute();

Retrofit也存在类似的支持。RetryPolicy支持各种配置。这适用于同步和异步执行并支持取消。

于 2022-02-15T16:05:34.800 回答