如何在 Apache http 客户端中设置连接超时?
我想使用 HTTPClient 运行线程安全的异步 HTTP 请求。我注意到它不尊重我的 CONNECTION_TIMEOUT
参数。
该代码是 ColdFusion / Java 的混合体。
client = loader.create("org.apache.http.impl.nio.client.DefaultHttpAsyncClient").init();
CoreConnectionPNames = loader.create("org.apache.http.params.CoreConnectionPNames");
client.getParams()
.setIntParameter(JavaCast("string", CoreConnectionPNames.SO_TIMEOUT), 10)
.setIntParameter(JavaCast("string", CoreConnectionPNames.CONNECTION_TIMEOUT), 10);
client.start();
request = loader.create("org.apache.http.client.methods.HttpGet").init("http://www.google.com");
future = client.execute(request, javacast("null", ""));
try {
response = future.get();
}
catch(e any) {}
client.getConnectionManager().shutdown();
无论我为 CONNECTION_TIMEOUT 提供什么,请求总是返回 200 OK。检查下面的输出。
- 如何设置有效的连接超时?
- CONNECTION_TIMEOUT 有什么作用吗?
输出
200 OK http://www.google.com/
200 OK http://www.google.com/
[snip]
5 requests using Async Client in: 2308 ms
I want to run thread safe, asynchronous HTTP requests using HTTPClient. I noticed that it does not respect my CONNECTION_TIMEOUT
argument.
The code is ColdFusion / Java hybrid.
client = loader.create("org.apache.http.impl.nio.client.DefaultHttpAsyncClient").init();
CoreConnectionPNames = loader.create("org.apache.http.params.CoreConnectionPNames");
client.getParams()
.setIntParameter(JavaCast("string", CoreConnectionPNames.SO_TIMEOUT), 10)
.setIntParameter(JavaCast("string", CoreConnectionPNames.CONNECTION_TIMEOUT), 10);
client.start();
request = loader.create("org.apache.http.client.methods.HttpGet").init("http://www.google.com");
future = client.execute(request, javacast("null", ""));
try {
response = future.get();
}
catch(e any) {}
client.getConnectionManager().shutdown();
Regardless of what I supply for CONNECTION_TIMEOUT, the requests always return 200 OK. Check the output below.
- How do I set an effective connection timeout?
- Does CONNECTION_TIMEOUT do anything?
Output
200 OK http://www.google.com/
200 OK http://www.google.com/
[snip]
5 requests using Async Client in: 2308 ms
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
apache 的 HttpClient 的文档有点参差不齐。在您的设置中尝试一下(它对我的版本 4 有效):
The documentation for apache's HttpClient is kind of spotty. Try this in your setup (it worked for me with version 4):
您必须使用框架的类方法定义 HttpParams 对象。
You have to define a HttpParams object using the framework's class methods.