httpclient 超时时间 等待时间 响应时间

HttpClient在使用中有两个超时时间。

一、连接超时:connectionTimeout
   1.指的是连接一个url的连接等待时间。
   2.设置方法为:
Java代码
  1. HttpClient client = new HttpClient();   
  2. HttpMethod method = new GetMethod("http://test.com");      
  3. client.getHttpConnectionManager().getParams().setConnectionTimeout(3000);    
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod("http://test.com");   
client.getHttpConnectionManager().getParams().setConnectionTimeout(3000);  

   3.测试的时候,将url改为一个不存在的url:“http://test.com”
   4:超时时间3000ms过后,系统报出异常。
     org.apache.commons.httpclient.ConnectTimeoutException: The host did not accept the connection within timeout of 3000 ms

二、读取数据超时:soTimeout
   1.指的是连接上一个url,获取response的返回等待时间
   2.设置方法伟:
Java代码
  1. HttpClient client = new HttpClient();   
  2. HttpMethod method = new GetMethod("http://localhost:8080/firstTest.htm?method=test");   
  3. client.getHttpConnectionManager().getParams().setSoTimeout(2000);  
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod("http://localhost:8080/firstTest.htm?method=test");
client.getHttpConnectionManager().getParams().setSoTimeout(2000);

   3.测试的时候的连接url为我本地开启的一个url,http://localhost:8080/firstTest.htm?method=test,在我这个测试url里,当访问到这个链接时,线程sleep一段时间,来模拟返回response超时。
Java代码
  1. @RequestMapping(params = "method=test")   
  2. public String testMethod(ModelMap model) {       
  3. try {       
  4.     Thread.sleep(3000);       
  5. catch (InterruptedException e) {       
  6.     // TODO Auto-generated catch block      
  7.     e.printStackTrace();       
  8. }       
  9.       System.out.println("call testMethod method.");       
  10.       model.addAttribute("name""test method");       
  11. return "test";       
  12.   }  
@RequestMapping(params = "method=test")
public String testMethod(ModelMap model) {    
try {    
    Thread.sleep(3000);    
} catch (InterruptedException e) {    
    // TODO Auto-generated catch block    
    e.printStackTrace();    
}    
      System.out.println("call testMethod method.");    
      model.addAttribute("name", "test method");    
return "test";    
  }


   4:将读取response返回超时时间设的时间比那个sleep时间短之后,运行程序给出异常:java.net.SocketTimeoutException: Read timed out

4.3版本不设置超时的话,一旦服务器没有响应,等待时间N久(>24小时)。  以上版本对4.3已经过时

4.3版本超时设置

1
2
3
4
5
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet= new HttpGet( "http://www.baidu.com" );//HTTP Get请求(POST雷同)
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout( 2000 ).setConnectTimeout( 2000 ).build(); //设置请求和传输超时时间
httpGet.setConfig(requestConfig);
httpClient.execute(httpGet); //执行请求

  • 7
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值