如何使用 OkHttp/Retrofit 重试 HTTP 请求?

新手上路,请多包涵

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

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

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

原文由 dev 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 853
2 个回答

对于改造 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.close()
                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);

原文由 Sinan Kozak 发布,翻译遵循 CC BY-SA 4.0 许可协议

Resilience4j 提供了一种高度可配置的方式来定义您的重试行为,并将改造适配器作为附加模块。

可用选项的示例:

 private final Retry retry = Retry.of("id", RetryConfig.<Response<String>>custom()
  .maxAttempts(2)
  .waitDuration(Duration.ofMillis(1000))
  .retryOnResult(response -> response.code() == 500)
  .retryOnException(e -> e instanceof WebServiceException)
  .retryExceptions(IOException.class, TimeoutException.class)
  .ignoreExceptions(BusinessException.class, OtherBusinessException.class)
  .failAfterMaxAttempts(true)
  .build());

请参阅 弹性 4j 文档,了解如何将其与 Retrofit 集成。

原文由 msung 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题