java 如何在时间间隔后使 HTTP 连接超时/断开连接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1925154/
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-10-29 18:33:05  来源:igfitidea点击:

How to make the HTTP connection timeout/disconnected after a time interval?

javahttpconnectionhttpclient

提问by mebada

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

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

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?

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

回答by ZZ Coder

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

HTTPClient 中涉及 2 个超时,请尝试同时设置,

  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 native Process timeout

java本机进程超时

回答by danben

The connection manager timeout triggers when the act of trying to get a connection from your connection manager takes too long. This is not the same as the timeout for the http connection itself. Use HttpClientParams.setSoTimeout() instead.

当尝试从连接管理器获取连接的操作时间过长时,会触发连接管理器超时。这与 http 连接本身的超时时间不同。改用 HttpClientParams.setSoTimeout()。

http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/params/HttpMethodParams.html#setSoTimeout%28int%29

http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/params/HttpMethodParams.html#setSoTimeout%28int%29

回答by Brian Agnew

Have you looked at setting SO_TIMEOUT?

你看过设置SO_TIMEOUT吗?

Sets the socket timeout (SO_TIMEOUT) in milliseconds to be used when executing the method. A timeout value of zero is interpreted as an infinite timeout.

设置执行方法时要使用的套接字超时 (SO_TIMEOUT) 以毫秒为单位。超时值为零被解释为无限超时。