我使用HttpClient来调用API并获得其响应,并且我设置了60秒的超时。在这60秒内,Java尝试每20秒重试一次连接到API,并显示异常。在60秒的最后一秒,它停止重试。
我的疑问是:这个I/O异常是由API引起的?由于我设置的超时值高于异常返回值(每20秒(。
这是代码和日志:
HttpClient client = new HttpClient();
GetMethod getMethod = new GetMethod(GET_TICKETS_URL);
getMethod.setRequestHeader("Content-Type", "application/json");
getMethod.setRequestHeader("Accept", "application/json");
getMethod.getParams().setSoTimeout(60000);
logger.info("Calling service: " + getMethod.getPath());
client.getHttpConnectionManager().getParams().setConnectionTimeout(60000);
client.getHttpConnectionManager().getParams().setSoTimeout(60000);
client.getParams().setSoTimeout(60000);
client.getParams().setConnectionManagerTimeout(60000);
int getTicketsResponse = client.executeMethod(getMethod);
[2020-08-27 13:41:25,215] pool-3-thread-1 br.com.pfm.tasks.baml.task Task INFO - Calling service: /
[2020-08-27 13:41:46,228] pool-3-thread-1 org.apache.commons.httpclient.HttpMethodDirector INFO - I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect
[2020-08-27 13:41:46,228] pool-3-thread-1 org.apache.commons.httpclient.HttpMethodDirector INFO - Retrying request
[2020-08-27 13:42:07,242] pool-3-thread-1 org.apache.commons.httpclient.HttpMethodDirector INFO - I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect
[2020-08-27 13:42:07,242] pool-3-thread-1 org.apache.commons.httpclient.HttpMethodDirector INFO - Retrying request
[2020-08-27 13:42:28,258] pool-3-thread-1 org.apache.commons.httpclient.HttpMethodDirector INFO - I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect
[2020-08-27 13:42:28,258] pool-3-thread-1 org.apache.commons.httpclient.HttpMethodDirector INFO - Retrying request
[2020-08-27 13:42:49,271] pool-3-thread-1 br.com.pfm.tasks.baml.task ERROR - java.net.ConnectException: Connection timed out: connect
当从url读取时出现问题时,会发生I/O异常,你能得到堆栈堆栈跟踪吗?它会提供有关该问题的详细信息,可能是服务器不可用或在http 400+中找不到任何东西
所以请把这个添加到你的catch块中,这将帮助你了解出了什么问题。
catch(Exception e)
{
e.printStacktrace();
}
根据此处提供的不完整信息,堆栈跟踪可能会显示失败点是您尝试启动HTTP事务的地方(实际上是告诉它进行head并连接(。
假设你已经在GetMethod中正确设置了所有内容(我无法判断(,我可以建议你检查一下你试图到达的目标是否可以从机器上到达吗?试试wget,或者如果它在桌面上,试着用浏览器访问它。如果这样做有效,很可能是你在GetMethod代码发布中设置错误,这对进一步解决问题非常有帮助。