I'm using the DefaultHTTPClient in Android to fetch pages. I'd like to trap 500 and 404 errors returned by the server but all I get is a java.io.IOException. How can I specifically trap those two errors?
Here's my code:
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;
}
You need to get 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
}
You can use status code comparison, like this:
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
}
But the important thing is that you need even so consume the HTTPEntity, otherwise your connection is not released back to the connection pool, what could lead to connection pool exhaustion. You already do this with the toString(entity), but if you don't wanna consume resources reading something that wouldn't be used, you can do this with the following instruction:
EntityUtils.consumeQuietly(resResponse.getEntity())
The documentation you can find here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With