在Java中,如果响应时间超过n秒,api是否重新运行http post请求?
我正在用Java调用RESTAPI,但有时响应中会偶尔出现延迟。因此,我想以某种方式检查响应是否花费了太长的时间(例如2秒或3秒),然后重新启动/重新运行http post请求,因为我不需要一个在等待响应时“卡住”的请求,而该响应可能会在很久很久以后出现
这是我到目前为止的一段代码:
private final CloseableHttpClient client;
HttpResponse response;
List<NameValuePair> parameters;
HttpPost post;
public String getRoleData(int roleid) {
this.post = new HttpPost(this.createUrl("role/eventdata"));
this.post.setHeader("apikey", this.apikey);
this.parameters = new ArrayList<>();
this.parameters.add(new BasicNameValuePair("roleid", String.valueOf(roleid)));
try {
post.setEntity(new UrlEncodedFormEntity(this.parameters));
this.response = client.execute(post);
String JsonResponse = EntityUtils.toString(this.response.getEntity(), StandardCharsets.UTF_8);
return JsonResponse;
} catch (UnsupportedEncodingException ex) {
System.out.println("API Unsupported instruction entry");
} catch (IOException ex) {
System.out.println("API IO issue");
}
return "Empty response";
}
# 1 楼答案
它应该与上面类似。检查RequestConfig部件&;异常处理部分。您可以在错误处理&;再试一次。我们正在为http客户端设置超时值。你可以浏览一些java文档来了解更多细节
顺便说一下,您使用的是POST方法,根据定义,它不是幂等的。因此,在再次运行相同的请求时,需要小心。服务器可能已经在您获得超时后处理了