How to retry HTTP requests with OkHttp/Retrofit?

后端 未结 13 742
一向
一向 2020-12-07 09:04

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

I don\'t find any request retry mechanism built-in to either of them. On searching more, I read OkHttp seems

13条回答
  •  鱼传尺愫
    2020-12-07 10:01

    A solution that worked for me on OkHttp 3.9.1 (considering other answers for this question):

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

提交回复
热议问题