HttpClient 4.5.1 - 多个请求的其他重试计数

时间:2016-02-24 14:14:23

标签: apache request apache-httpclient-4.x

我有一个http客户端的单例实例,并将为每个执行请求设置重试次数。有解决方案吗?

我发现只在httpClientBuilder中设置了DefaultHttpRequestRetryHandler。

httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(10, false));

但这适用于所有请求相同(10)

1 个答案:

答案 0 :(得分:1)

可以始终使用自定义上下文属性来自定义HttpClient行为

CloseableHttpClient httpClient = HttpClientBuilder.create()
        .setRetryHandler((exception, executionCount, context) -> executionCount < (Integer) context.getAttribute("retry.count"))
        .build();
HttpClientContext clientContext = HttpClientContext.create();
clientContext.setAttribute("retry.count", 4);
HttpGet get1 = new HttpGet("http://host/");
try (CloseableHttpResponse response1 = httpClient.execute(get1)) {
    EntityUtils.consume(response1.getEntity());
}
clientContext.setAttribute("retry.count", 10);
HttpGet get2 = new HttpGet("http://host/");
try (CloseableHttpResponse response2 = httpClient.execute(get2)) {
    EntityUtils.consume(response2.getEntity());
}