Java 使用 Apache HttpClient,为什么我的连接超时不起作用?

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

With Apache HttpClient, why isn't my connection timeout working?

javahttpclient

提问by

My implementation of httpclient occasionally throws an exception when calling doGetConnection(). However, I have the following timeout set

我的 httpclient 实现在调用 doGetConnection() 时偶尔会抛出异常。但是,我设置了以下超时

_moHttpClient.setHttpConnectionFactoryTimeout(30000);

it looks almost like my timeout is not being picked up. Is there anywhere else I need to set a timeout to ensure this behaviour does not re-occur

看起来我的超时几乎没有被接受。是否还有其他地方需要设置超时以确保不会再次发生此行为

回答by JeeBee

    HttpConnectionManagerParams cmparams = new HttpConnectionManagerParams();
    cmparams.setSoTimeout(10000);
    cmparams.setTcpNoDelay(true);
    HttpConnectionManager manager = new SimpleHttpConnectionManager();
    manager.setParams(cmparams);
    params = new HttpClientParams();
    params.setSoTimeout(5000);
    client = new HttpClient(params, manager);

I wonder why I have two different SoTimeouts set. Maybe I was trying to find out which one was actually active, as I had the same problems as you when I used it.

我想知道为什么我设置了两个不同的 SoTimeouts。也许我想找出哪个是真正活跃的,因为我在使用它时遇到了与您相同的问题。

The above is in live code at our place right now, but I cannot say whether it works because it's correct, or because providence is smiling down on me (and the other end is usually always available).

以上是我们现在的实时代码,但我不能说它是否有效,因为它是正确的,或者因为天意对我微笑(而另一端通常总是可用的)。

回答by Alexander Pavlenko

cmparams.setSoTimeout(10000);

cmparams.setSoTimeout(10000);

This one is for all HttpClient by default.

默认情况下,这是针对所有 HttpClient 的。

params.setSoTimeout(5000);

params.setSoTimeout(5000);

And this one is for a particular httpclient.

这是针对特定的 httpclient。

回答by Brian Agnew

What exception are you getting thrown ?

你会抛出什么异常?

Don't forget you have twotimeouts to change/check. From HttpConnectionParams

不要忘记您有两个超时要更改/检查。从HttpConnectionParams

setConnectionTimeout()
setSoTimeout()

so you can control how long you wait for a connection to the server, and how long operations on the socket can take before timing out.

因此您可以控制等待连接到服务器的时间,以及在超时之前对套接字的操作需要多长时间。