天天看點

HttpClient connectionTimeout

HttpClient在使用中有兩個逾時時間 差別(轉)

HttpClient在使用中有兩個逾時時間。 

一、連接配接逾時:connectionTimeout 

   1.指的是連接配接一個url的連接配接等待時間。 

   2.設定方法為: 

Java代碼  

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

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這兩個逾時時間一定要加上,不加就很可能悲劇的了。

繼續閱讀