Java 如果请求超时,HttpClient 会多次执行请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23054289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 20:19:43  来源:igfitidea点击:

HttpClient executes requests multiple time if request timed out

javaandroidhttpclientconnection-timeout

提问by Geek

HttpClientexecutes request 4 times if it times out. If it does not time out then it is working fine. Is it related to HttpClient?

HttpClient如果超时,则执行请求 4 次。如果它没有超时,那么它工作正常。和 有关系HttpClient吗?

采纳答案by Geek

I found that it is HttpClient's default behaviour to execute requests 4 times if it fails. I am not sure about other kind of failures but at least with time out.

我发现HttpClient如果失败则执行请求 4 次是它的默认行为。我不确定其他类型的失败,但至少有超时。

To disable this behaviour do this :

要禁用此行为,请执行以下操作:

DefaultHttpClient client = new DefaultHttpClient();
// Disable default behavior of HttpClient of retrying requests in case of failure
((AbstractHttpClient) client).setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

Here retry count is set to 0to disable retry.

这里重试计数设置0为禁用重试。

I found solution from this blog.

我从这个博客中找到了解决方案。

回答by Juned Ahsan

Apache HttpClient tries to connect 5 times in case of transport exception. Here is what docsays:

Apache HttpClient 在传输异常的情况下尝试连接 5 次。这是医生所说的:

HttpClient will automatically retry up to 5 times those methods that fail with a transport exception while the HTTP request is still being transmitted to the target server (i.e. the request has not been fully transmitted to the server).

当 HTTP 请求仍在传输到目标服务器时(即请求尚未完全传输到服务器),HttpClient 将自动重试最多 5 次那些因传输异常而失败的方法。

To change this behaviour you need to implement HttpMethodRetryHandlerinterface

要更改此行为,您需要实现HttpMethodRetryHandler接口

回答by Kehinde Adedamola Shittu

This resolved the issue for me. Using httpclient 4.3 and above.

这为我解决了这个问题。使用 httpclient 4.3 及更高版本。

HttpClientBuilder.create().disableAutomaticRetries().build();