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

发布于 2024-08-15 10:57:57 字数 386 浏览 6 评论 0原文

我是 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);

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

要走干脆点 2024-08-22 10:57:57

HTTPClient 涉及 2 个超时,请尝试设置这两个超时,

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

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

java 本机进程超时

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

久隐师 2024-08-22 10:57:57

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

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

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://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/params/HttpMethodParams.html#setSoTimeout%28int%29

-柠檬树下少年和吉他 2024-08-22 10:57:57

您是否看过设置 SO_TIMEOUT

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

Have you looked at setting 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文