2012-09-09 35 views
3

我在Android中使用DefaultHTTPClient來抓取頁面。我想捕獲服務器返回的500和404錯誤,但我得到的只是一個java.io.IOException。我怎樣才能專門捕捉這兩個錯誤?使用tth時捕獲404和500錯誤DefaultHTTPClient

這裏是我的代碼:

public String doGet(String strUrl, List<NameValuePair> lstParams) throws Exception { 

    Integer intTry = 0; 

    while (intTry < 3) { 

     intTry += 1; 

     try { 

      String strResponse = null; 
      HttpGet htpGet = new HttpGet(strUrl); 
      DefaultHttpClient dhcClient = new DefaultHttpClient(); 
      dhcClient.addResponseInterceptor(new MakeCacheable(), 0); 
      HttpResponse resResponse = dhcClient.execute(htpGet); 
      strResponse = EntityUtils.toString(resResponse.getEntity()); 
      return strResponse; 

     } catch (Exception e) { 

      if (intTry < 3) { 
       Log.v("generics.Indexer", String.format("Attempt #%d", intTry)); 
      } else {     
       throw e;      
      } 

     } 

    } 

    return null; 

} 

回答

7

你需要得到statusCode

HttpResponse resResponse = dhcClient.execute(htpGet); 
StatusLine statusLine = resResponse.getStatusLine(); 
int statusCode = statusLine.getStatusCode(); 
if (statusCode == HttpURLConnection.HTTP_OK) { 
    // Here status code is 200 and you can get normal response 
} else { 
    // Here status code may be equal to 404, 500 or any other error 
} 
+0

+1,我會建議改變你的代碼片段的評論,這實際上意味着你會處理其他塊的200響應以外的所有其他東西,因爲'java.net.HttpURLConnection.HTTP_OK'是一個常數值' 200' –

+0

除了200以外的其他所有內容都由else塊(包括3xx,2xx(除200)和1xx狀態類)處理,而不僅僅是錯誤。 –

0

我用

if (response.getStatusLine().toString().compareTo(getString(R.string.api_status_ok)) == 0) 

檢查響應代碼。當一切順利時,它應該是HTTP/1.1 200 OK。您可以輕鬆創建一個開關來管理不同的案例。

2

您可以使用狀態碼進行比較,就像這樣:

StatusLine statusLine = resResponse.getStatusLine(); 
int statusCode = statusLine.getStatusCode(); 
if (statusCode >= 400 && statusCode < 600) { 
    // some handling for 4xx and 5xx errors 
} else { 
    // when not 4xx or 5xx errors 
} 

但重要的是,你需要即便如此消耗HTTPEntity,否則你的連接不會釋放回連接池,可能會導致連接池耗盡。你已經做到這一點與toString(entity),但如果你不想消耗資源讀書東西不會被使用,你可以用下面的命令做到這一點:

EntityUtils.consumeQuietly(resResponse.getEntity()) 

的文檔,你可以找到here