How to make HttpClient to retry HttpRequest at arbitrary HTTP status in org.apache.http.client

ʻOrg.apache.http.client` Make an HTTP request from an HTTP client generated using I want to retry depending on the returned HTTP status (200, 404, 503, etc.) There is a time to say, and the solution at that time.

(The project member told me that it was hard to write the version, so I will write the working version for the time being.)

It has been confirmed to work in the environment using!

Instead of a memorandum, hoping that someday it will help someone.



RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).build();

final HttpClientBuilder hcBuilder = HttpClientBuilder.create()
		.setDefaultRequestConfig(requestConfig) 
		//Retry when HTTP IO error occurs
		.setRetryHandler(new DefaultHttpRequestRetryHandler()) 
		//Whether to retry or not depends on the boolean value of retryRequest at the time of HTTP request
		.setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
			@Override
			public boolean retryRequest(
					final HttpResponse response, final int executionCount, final HttpContext context) {
				int statusCode = response.getStatusLine().getStatusCode();
				return Arrays.asList(RETRY_HTTP_STATUSES).contains(statusCode)
						&& executionCount < MAX_RETRY_COUNT;
			}

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

Needless to say, but if you supplement -RETRY_HTTP_STATUSES is an array of ʻInteger type, and define the HTTP status code group that you want to retry. -MAX_RETRY_COUNT defines a maximum number of retries. · RETRY_INTERVAL_MILL_SEC defines the millisecond of the retry interval.

Now even a copy / paste programmer can write a retry process!

Recommended Posts

How to make HttpClient to retry HttpRequest at arbitrary HTTP status in org.apache.http.client
How to make a judgment method to search for an arbitrary character in an array
How to make a follow function in Rails
How to make an image partially transparent in Processing
How to make shaded-jar
How to change application.properties settings at boot time in Spring boot
Java --How to make JTable
[Rails] How to make seed
How to make a jar file with no dependencies in Maven
How to call multiple names at once in the same category