2010-07-09 59 views
2

朋友,如何在android中實現請求超時?

我遇到了一個問題,當我嘗試調用webservice並且服務器/ internet不可用時。看起來 連接需要很長時間才能超時

我可以手動設置timout來向用戶顯示錯誤消息嗎?

任何幫助,將不勝感激。

回答

1

設置您的HttpClient這種方式。

BasicHttpParams httpParams = new BasicHttpParams(); 
    ConnManagerParams.setTimeout(httpParams, connectionTimeoutInMs); 
    httpClient = new DefaultHttpClient(httpParams); 
+0

這對我有效,但它沒有拋出異常,此外,狀態解析爲200 OK。 – mobibob 2010-08-20 16:27:10

+0

此代碼不適用於我。請幫幫我 – 2013-03-25 14:14:40

4

你可以嘗試這樣來做:

URL url; 
URLConnection connection; 
try { 
    url = new URL("http://foo.bar.com"); 
    connection = url.openConnection(); 
    connection.setConnectTimeout(3000); // set 3 seconds for timeout 
    connection.connect(); 
}catch(SocketTimeoutException ss){ 
    // show message to the user 
} 
0
This will work always... 


try  { 
    HttpParams httpParams = new BasicHttpParams(); 
    HttpConnectionParams.setConnectionTimeout(httpParams, Constants.CONN_TIMEOUT); 
    HttpConnectionParams.setSoTimeout(httpParams, Constants.SOCKET_CONN_TIMEOUT); 
    DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); 
    url = "write-your-web-url-here";    
    HttpGet httpGet = new HttpGet(url); 
    response = httpClient.execute(httpGet); 
    HttpEntity entity = response.getEntity`enter code here`(); 
    if(entity != null) is = entity.getContent(); 
}catch(ConnectTimeoutException timeoutException) { 
    System.out.println("ConnectTimeoutException Occured..."); 
}catch(SocketTimeoutException socketTimeoutException) { 
    System.out.println("SocketTimeoutException Occured...") 
}catch(Exception e){ 
    System.out.println("Exception Occured..."); 
} 
4

有兩種超時:

  1. 連接超時

即直到建立了連接的時間

  • Socket Timeout
  • 這是等待接收數據的超時時間,將它們中的任何一個設置爲0意味着無限超時,並且這是兩者的默認值,因此設置其中一個不會影響另一個。

    try{ 
    
        BasicHttpParams httpParams = new BasicHttpParams(); 
    
        //this will set socket timeout 
        HttpConnectionParams.setSoTimeout(httpParams, /*say*/ 3000); 
    
        //this will set connection timeout 
        HttpConnectionParams.setConnectionTimeout(httpParams, 3000); 
    
        client = new DefaultHttpClient(httpParams); 
    
        String url = "some-url";    
        HttpGet httpGet = new HttpGet(url); 
        response = httpClient.execute(httpGet); 
        //here use the received response 
    
        } 
        catch(ConnectTimeoutException ex) { 
         //handle connection timeout here 
        } 
        catch(SocketTimeoutException ex) { 
         //handle socket timeout here 
        }