Dealing with Exceptions

Dealing with exceptions is part of any program, but software that makes use of external services (such as HTTP services) must pay additional attention to exceptions because the potential for errors is magnified. There are several types of exceptions that you can expect while making use of HTTP services. These include transport exceptions, protocol exceptions, and timeouts. You should understand when these exceptions could occur.

Transport exceptions can occur due to a number of reasons, but the most likely scenario (with a mobile device) is poor network connectivity. Protocol exceptions are exceptions at the HTTP protocol layer. These include authentication errors, invalid cookies, and so on. You can expect to see protocol exceptions if, for example, you have to supply login credentials as part of your HTTP request but fail to do so. Timeouts, with respect to HTTP calls, come in two flavors: connection timeouts and socket timeouts. A connection timeout can occur if the HttpClient is not able to connect to the HTTP server—if, for example, the URL is not correct or the server is not available. A socket timeout can occur if the HttpClient fails to receive a response within a defined time period. In other words, the HttpClient was able to connect to the server, but the server failed to return a response within the allocated time limit.

Now that you understand the types of exceptions that might occur, how do you deal with them? Fortunately, the HttpClient is a robust framework that takes most of the burden off your shoulders. In fact, the only exception types that you'll have to worry about are the ones that you'll be able to manage easily. As we said earlier, there are three types of exceptions that you can expect: transport exceptions, protocol exceptions, and timeouts. The HttpClient takes care of transport exceptions by detecting transport issues and retrying requests (which works very well with this type of exception). Protocol exceptions are exceptions that can generally be flushed out during development. Timeouts are the ones that you'll have to deal with. A simple and effective approach to dealing with both types of timeouts—connection timeouts and socket timeouts—is to wrap the execute method of your HTTP request with a try/catch and then retry if a failure occurs. This is demonstrated in Listing 8-5.

Listing 8-5. Implementing a Simple Retry Technique to Deal with Timeouts import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI;

import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient;

public class TestHttpGet {

public String executeHttpGetWithRetry() throws Exception { int retry = 3;

int count = 0; while (count < retry) { count += 1; try {

String response = executeHttpGet();

* if we get here, that means we were successful and we can

return response; } catch (Exception e) {

* if we have exhausted our retry limit

* we have retries remaining, so log the message and go * again.

System.out.println(e.getMessage()); } else {

System.out.println("could not succeed with retry..."); throw e;

return null;

public String executeHttpGet() throws Exception { BufferedReader in = null; try {

HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet();

request.setURI(new URI("http://code.google.com/android/")); HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity() .getContent()));

StringBuffer sb = new StringBuffer(""); String line = "";

String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL);

String result = sb.toString(); return result; } finally {

in.close(); } catch (IOException e) { e.printStackTrace();

The code in Listing 8-5 shows how you can implement a simple retry technique to recover from timeouts when making HTTP calls. The listing shows two methods: one that executes an HTTP GET (executeHttpGet()), and another that wraps this method with the retry logic (executeHttpGetWithRetry()). The logic is very simple. We set the number of retries we want to attempt to 3, and then we enter a while loop. Within the loop, we execute the request. Note that the request is wrapped with a try/catch block, and in the catch block we check whether we have exhausted the number of retry attempts.

When using the HttpClient as part of a real-world application, you need to pay some attention to multithreading issues that might come up. Let's delve into this now.

0 0

Post a comment