HttpClient connectionTimeout

转自:http://www.cnblogs.com/carlosk/archive/2013/03/12/2956502.htmlhtml

前几天服务器端的产品经理跑来问我是否有作请求超时和响应超时的处理。我一脸迷茫,直接就说:我作了开发这么久,从不知道什么是请求超时什么是响应超时。java

后来我静下来仔细想一想,确实应该有请求超时和响应超时这两个概念,否则会出不少问题的。
而后花了一些时间仔细查了下资料。确实是如此。
 
ConnectException : 指的是服务器请求超时
SocketTimeoutException:指的是服务器响应超时
能够在代码里设置
 //请求超时
        httpclient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,reqTimeout);
        //响应超时
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, resTimeout);
 
你们若是之后作安全级别高的项目可能会碰到我这样的问题。我说明下。
当一笔交易,若是请求失败,那能够容许用户再次提交。
若是是响应失败,那就说明用户提交成功了,应该防止用户再次提交

HttpClient在使用中有两个超时时间 区别apache

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

1、链接超时:connectionTimeout    1.指的是链接一个url的链接等待时间。    2.设置方法为: 服务器

Java代码  app

HttpClient client = new HttpClient();  测试

HttpMethod method = new GetMethod("http://test.com");     url

client.getHttpConnectionManager().getParams().setConnectionTimeout(3000);    .net

   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 2、读取数据超时:soTimeout    1.指的是链接上一个url,获取response的返回等待时间    2.设置方法伟: 线程

Java代码  

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代码  

@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 提醒:之后再写httpClient这两个超时时间必定要加上,不加就极可能悲剧的了。

相关文章
相关标签/搜索