如何重试HTTP请求与OkHttp /改造? [英] How to retry HTTP requests with OkHttp/Retrofit?

查看:2483
本文介绍了如何重试HTTP请求与OkHttp /改造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用改造/ OkHttp(1.6)在我的Andr​​oid项目。

I am using Retrofit/OkHttp (1.6) in my Android project.

我没有找到内置在任一其中的任何请求重试机制。在寻找更多的,我读OkHttp似乎有无声重试。我没有看到任何我的连接,这种情况发生(HTTP或HTTPS)。如何配置重试与okclient?

I don't find any request retry mechanism built-in to either of them. On searching more, I read OkHttp seems to have silent-retries. I don't see that happening on any of my connections (HTTP or HTTPS). How to configure retries with okclient ?

目前,我捕获异常和重试保持计数器变量。

For now, I am catching exceptions and retrying maintaining a counter variable.

推荐答案

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

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

和使用它,而创造RestAdapter。

And use it while creating RestAdapter.

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

对于改造2.X;

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

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

这篇关于如何重试HTTP请求与OkHttp /改造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆