如何在一段时间后使 HTTP 连接超时/断开连接?

2022-01-24 00:00:00 connection http httpclient java

我是 Apache HttpClient 的新手,我使用以下代码在一定时间间隔后获取 HTTP 连接超时(断开连接):

I am new in Apache HttpClient, I used the following code to get the HTTP connection timeout (disconnected) after certain time interval:

PostMethod method = new PostMethod(authURL);
HttpClient client = new HttpClient();
HttpClientParams params= new HttpClientParams();
params.setParameter(params.CONNECTION_MANAGER_TIMEOUT, 10); //10 Nano second
client.executeMethod(method);

但它等待超过一分钟而没有任何希望超时/断开连接?问题可能出在哪里?

but it wait for more than one minute without any hope to timeout/disconnect? Where can the problem be?

推荐答案

HTTPClient有2个超时,两个都试试,

There are 2 timeouts involved in HTTPClient, try to set both,

  client.getHttpConnectionManager().
        getParams().setConnectionTimeout(5000);
  client.getHttpConnectionManager().
        getParams().setSoTimeout(5000);

但是,如果连接卡在本机套接字调用中,则这些值将被忽略.因此,您可能必须在不同的线程中运行请求,以便将其超时.请参阅我对这个问题的回答,了解如何做到这一点,

However, the values will be ignored if the connection is stuck in a native socket call. So you might have to run the request in a different thread so you can time it out. See my answer to this question on how to do that,

java原生进程超时

相关文章