加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何在Apache http客户端中设置连接超时?

发布时间:2020-12-14 05:26:39 所属栏目:Java 来源:网络整理
导读:参见英文答案 With Apache HttpClient,why isn’t my connection timeout working?3 我想使用 HTTPClient运行线程安全的异步HTTP请求.我注意到它不尊重我的CONNECTION_TIMEOUT参数. 代码是ColdFusion / Java混合. client = loader.create("org.apache.http.i
参见英文答案 > With Apache HttpClient,why isn’t my connection timeout working?3
我想使用 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

解决方法

apache的HttpClient的文档很多.在你的设置中尝试这个(对于我,版本4)
HttpConnectionParams.setConnectionTimeout(params,10000);
HttpConnectionParams.setSoTimeout(params,10000);

... set more parameters here if you want to ...

SchemeRegistry schemeRegistry = new SchemeRegistry();

.. do whatever you ant with the scheme registry here ...

ThreadSafeClientConnManager connectionManager = new ThreadSafeClientConnManager(params,schemeRegistry);

client = new DefaultHttpClient(connectionManager,params);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读