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

前端之家收集整理的这篇文章主要介绍了java – 如何在Apache http客户端中设置连接超时?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > With Apache HttpClient,why isn’t my connection timeout working?3
我想使用 HTTPClient运行线程安全的异步HTTP请求.我注意到它不尊重我的CONNECTION_TIMEOUT参数.

代码是ColdFusion / Java混合.

  1. client = loader.create("org.apache.http.impl.nio.client.DefaultHttpAsyncClient").init();
  2. CoreConnectionPNames = loader.create("org.apache.http.params.CoreConnectionPNames");
  3.  
  4. client.getParams()
  5. .setIntParameter(JavaCast("string",CoreConnectionPNames.SO_TIMEOUT),10)
  6. .setIntParameter(JavaCast("string",CoreConnectionPNames.CONNECTION_TIMEOUT),10);
  7.  
  8. client.start();
  9.  
  10. request = loader.create("org.apache.http.client.methods.HttpGet").init("http://www.google.com");
  11. future = client.execute(request,javacast("null",""));
  12.  
  13. try {
  14. response = future.get();
  15. }
  16. catch(e any) {}
  17.  
  18. client.getConnectionManager().shutdown();

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

>如何设置有效的连接超时?
> CONNECTION_TIMEOUT是否做任何事情?

产量

  1. 200 OK http://www.google.com/
  2.  
  3. 200 OK http://www.google.com/
  4.  
  5. [snip]
  6.  
  7. 5 requests using Async Client in: 2308 ms

解决方法

apache的HttpClient的文档很多.在你的设置中尝试这个(对于我,版本4)
  1. HttpConnectionParams.setConnectionTimeout(params,10000);
  2. HttpConnectionParams.setSoTimeout(params,10000);
  3.  
  4. ... set more parameters here if you want to ...
  5.  
  6. SchemeRegistry schemeRegistry = new SchemeRegistry();
  7.  
  8. .. do whatever you ant with the scheme registry here ...
  9.  
  10. ThreadSafeClientConnManager connectionManager = new ThreadSafeClientConnManager(params,schemeRegistry);
  11.  
  12. client = new DefaultHttpClient(connectionManager,params);

猜你在找的Java相关文章