我在Android中使用DefaultHTTPClient来获取页面。我想捕获服务器返回的500和404错误,但我得到的只是一个java.io.IOException。我该如何特别地捕获这两个错误?

这是我的代码:

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;

}

最佳答案

您需要获取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
}

08-17 11:03