HttpClient在使用中有兩個超時時間 區別
阿新 • • 發佈:2019-02-14
HttpClient在使用中有兩個超時時間。
一、連線超時:connectionTimeout
1.指的是連線一個url的連線等待時間。
2.設定方法為:
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.設定方法:
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超時。
@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這兩個超時時間一定要加上,不加就很可能悲劇的了。
一、連線超時:connectionTimeout
1.指的是連線一個url的連線等待時間。
2.設定方法為:
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.設定方法:
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超時。
@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這兩個超時時間一定要加上,不加就很可能悲劇的了。