java - Apache HTTP 客户端:未捕获 NoHttpResponseException 异常?
问题描述
NoHttpResponseException
如果被捕获,我想获取发送请求的重试总次数。我尝试使用 try-catch 块来实现该行为并且有一个奇怪的行为:
- 在我实现此行为之前,抛出异常并且程序中断。
- 我实现了这个行为后,不再抛出异常,程序正常运行。但是,该
catch
部分中的代码似乎并未真正执行:
int retry = 0;
final int MAX_RETRY = 1000;
String response = null;
JsonObject responseInJson = null;
while(true) {
try {
response = httpClient.execute(httpPost, responseHandler);
break;
} catch (IOException exception) {
if(exception instanceof NoHttpResponseException) {
retry++;
System.out.println("Retry for the " + retry + " time(s)");
if(retry == MAX_RETRY) {
throw exception;
}
} else {
System.out.println("Another exception occured");
throw exception;
}
}
}
我的班级有一个属性:
protected CloseableHttpClient httpClient;
属性在构造函数中初始化:
public AbstractData() {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(28800000)
.setConnectTimeout(28800000)
.setSocketTimeout(28800000)
.build();
this.httpClient = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setMaxConnPerRoute(4)
.setMaxConnTotal(4)
.build();
}
我的问题是,我在 try-catch 块中实现行为的方式是否存在任何逻辑错误?并且有没有更好的方法来直接改变DefaultHttpRequestRetryHandler
执行此行为(我试图查找并没有找到一个示例来检查发送请求的重试次数)。
解决方案
推荐阅读
- apache-kafka - Windows 上的 Kafka Connect for Oracle 设置
- python - 为什么我的代码运行相同的列表,即使它甚至没有被使用?
- angular - Rxjs - 带有按钮的表格,在请求之前按下最后一个按钮后等待一段时间
- azure - Azure 事件中心限制及其与纯 Kafka 群集的比较
- html - 在鼠标单击事件期间执行不需要的组件方法
- informix - 创建一个数组/列表并使用 for 循环在 informix 中打印
- c++ - 通过引用传递的二维向量的就地转置
- javascript - 同一个 onclick 事件在论坛中多次出现 - 需要自动的唯一 ID?
- javascript - 有没有更优雅的方式将参数传递给链式承诺
- java - 什么是分组通量,我们如何使用它?