改造:我如何重试请求再次从okhttp拦截器?

2022-01-28 10:15:39 标签 androidretrofitretrofit2okhttpinterceptor

我创建了一个拦截器。在某些情况下,我想重试请求'n'的次数,我如何做到这一点?

class NetworkErrorHandler constructor():  Interceptor {
    //Central error handling block for errors which has impact all over the app
    override fun intercept(chain: Interceptor.Chain): Response {
        val request =  chain.request()
        var response = chain.proceed(request) 
        return  
            when (response.code) {
                401 -> { 
                    response
                }
                200 ->{  
                    response
                }
                else -> { 
                        var tryCount = 0
                        while (tryCount < 3) {
                            try { 
                                response = chain.proceed(request)
                                tryCount++
                            }catch (e: java.lang.Exception){
                                tryCount++
                            }
                        }  
                    response
                }
            } 
    }
}

它给了我这个错误:

Suppressed: java.lang.IllegalStateException: network interceptor must call proceed() exactly once

我必须在这里做这个吗,如果是,那怎么做?

###我认为你从这个问题指导自己如何重试OkHttp/Retrofit HTTP请求?(如果没有,我建议你去做)。代码上的问题是,while只受trycount限制,而不受响应结果的限制。尝试在那里添加关于响应状态的验证,这样它就不会并行执行。proceed方法两次。

// try the request
Response response = chain.proceed(request);
int tryCount = 0;
while (!response.isSuccessful() && tryCount < 3) {

### #所以我能够通过使用这一行从拦截器进行另一个调用

response.close()      
chain.call().clone().execute()
                

根据问题的完整代码:

//Central error handling block for errors which has impact all over the app
class NetworkErrorHandler constructor(): Interceptor {
        var tryCount = 0
        override fun intercept(chain: Interceptor.Chain): Response {
            val request = chain.request()
            var response = chain.proceed(request)
            return
            when(response.code) {
                401 - > {
                    response
                }
                200 - > {
                    response
                }
                else - > {
                    if (tryCount < 3) {
                        Thread.sleep(2000)
                        tryCount++
                        response.close()
                        chain.call().clone().execute()
                    }
                    response.newBuilder()
                    .code(401) // Whatever code
                    .body("".toResponseBody(null)) // Whatever body
                    .protocol(Protocol.HTTP_2)
                    .message("Network Error")
                    .request(chain.request())
                    .build()
                }
            }
        } 

###我是这样做的:

@Slf4j
public class HttpRetryInterceptor implements Interceptor {
    @Override
    public @NotNull Response intercept(Chain chain) throws IOException {
        log.error("Making request for the first time.");
        var request = chain.request();
        Response response = null;
        boolean responseOK = false;
        byte tryCount = 0;
        while (!responseOK && tryCount < 3) {
            try {
                Thread.sleep(5000 * tryCount);
                response = chain.proceed(request);
                log.info("Response is: {}",response);
                log.info("Response message: {}",response.message());
                responseOK = response.isSuccessful();
            }catch (Exception e){
                e.printStackTrace();
                log.error("Request was not successful: {} . Retrying." , tryCount);
            }finally{
                assert response != null;
                response.close();
                tryCount++;
            }
        }
        return response != null ? response : chain.proceed(request);
    }
}

然后我添加我的拦截器到我的客户端与一些类似:new OkHttpClient。Builder()。addInterceptor(新HttpRetryInterceptor ()) 。build ()

阅读全文

▼ 版权说明

相关文章也很精彩
推荐内容
更多标签
相关热门
全站排行
随便看看

错说 cuoshuo.com —— 程序员的报错记录

部分内容根据CC版权协议转载;网站内容仅供参考,生产环境使用务必查阅官方文档

辽ICP备19011660号-5

×

扫码关注公众号:职场神器
发送: 1
获取永久解锁本站全部文章的验证码