Timeout between request retries Apache HttpClient

snowindy picture snowindy · Jan 31, 2018 · Viewed 9.6k times · Source

Could somebody share how to configure modern HttpClient 4.5.3 to retry failed requests and wait for some time before each retry?

So far it looks like I got it correctly that .setRetryHandler(new DefaultHttpRequestRetryHandler(X, false)) will allow to retry requests X times.

But I cannot understand how to configure backoff: .setConnectionBackoffStrategy() / .setBackoffManager() according to JavaDocs regulate something else, not timeout between retries.

Answer

ok2c picture ok2c · Feb 1, 2018

BackoffManager / ConnectionBackoffStrategy combo can be used to dynamically increase or decrease max connection per route limits based on rate of I/O errors and 503 responses. They have no influence on request execution and cannot be used to control request re-execution

This is the best one can do with HC 4.x APIs

CloseableHttpClient client = HttpClientBuilder.create()
        .setRetryHandler(new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                return executionCount <= maxRetries &&
                        exception instanceof SocketException;
            }
        })
        .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
            @Override
            public boolean retryRequest(HttpResponse response, int executionCount, HttpContext context) {
                return executionCount <= maxRetries &&
                        response.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE;
            }

            @Override
            public long getRetryInterval() {
                return 100;
            }
        })
        .build();

Please note there is presently no elegant way of enforcing a delay between request execution attempts in case of an I/O error or dynamically adjusting the retry interval based on request route.