2011-10-15 163 views
11

我想要運行使用HTTPClient線程安全的,異步HTTP請求。我注意到它不尊重我的CONNECTION_TIMEOUT論點。如何在Apache HTTP客戶端中設置連接超時?

的代碼的ColdFusion/Java的混合體。無論什麼樣的我供應CONNECTION_TIMEOUT

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

,請求總是返回200 OK。檢查下面的輸出。

  1. 如何設置一個有效的連接超時?
  2. 不CONNECTION_TIMEOUT做什麼?

輸出

200 OK http://www.google.com/ 

200 OK http://www.google.com/ 

[snip] 

5 requests using Async Client in: 2308 ms 

回答

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

感謝。我正在嘗試你的代碼,但需要額外的工作才能將它轉換爲CF.和我一起裸露。在前兩個linse中'HTTPConnectionParams'引用了我需要創建的一個對象。可能是'org.apache.http.params。*'但你提供給'setConnectionTimeout'的'params'參數來自哪裏呢?我不能把它扔到那裏,否則它會拋出一個'params is undefined'錯誤...對不起,如果這聽起來很傻,但是使用java/CF混合代碼是很乏味的。另外,SchemeRegistry對象是否必需,我可以將其忽略嗎? – Mohamad

+0

HttpParams params = new BasicHttpParams();這裏有一些更多的信息:http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html和javadoc的是在這裏:http://hc.apache.org/httpcomponents-core-ga /httpcore/apidocs/org/apache/http/params/HttpParams.html – Seth

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); 
相關問題