轉自:http://www.cnblogs.com/carlosk/archive/2013/03/12/2956502.htmlhtml
前幾天服務器端的產品經理跑來問我是否有作請求超時和響應超時的處理。我一臉迷茫,直接就說:我作了開發這麼久,從不知道什麼是請求超時什麼是響應超時。java
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這兩個超時時間必定要加上,不加就極可能悲劇的了。