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

时间:2011-10-15 14:23:54

标签: java http httpclient

我想使用HTTPClient运行线程安全的异步HTTP请求。我注意到它不尊重我的CONNECTION_TIMEOUT参数。

代码是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();

无论我为CONNECTION_TIMEOUT提供什么,请求总是返回200 OK。检查下面的输出。

  1. 如何设置有效的连接超时?
  2. CONNECTION_TIMEOUT会做什么吗?
  3. 输出

    200 OK http://www.google.com/
    
    200 OK http://www.google.com/
    
    [snip]
    
    5 requests using Async Client in: 2308 ms
    

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

您必须使用框架的类方法定义HttpParams对象。

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpConnectionParams.setConnectionTimeout(params, 2000);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        HttpClient client = DefaultHttpClient(ccm, params);
相关问题