HTTP Operations via Apache Commons

The first step to using HttpClient is, not surprisingly, to create an HttpClient object. The client object handles all HTTP requests upon your behalf.

Those requests are bundled up into HttpMethod instances, with different HttpMethod subclasses for each different HTTP verb (e.g., GetMethod for HTTP get requests). You create an HttpMethod subclass instance, fill in the URL to retrieve and other configuration data (e.g., form values if you are doing an HTTP post via PostMethod), then pass the method to the client to actually make the HTTP request.

The request will, at minimum, give you an HTTP response code (e.g., 200 for OK) and various HTTP headers (e.g., Set-Cookie). In many cases, you will also be given the body of the response, which you can obtain as a byte array, a String, or an InputStream for later processing.

When you are done with the request, close the InputStream (if that's how you got the response body), then invoke releaseConnection() on the method object, to drop the HTTP connection.

For example, let's take a look at the Weather sample project. This implements an activity that retrieves weather data for your current location from the National Weather Service (NOTE: this probably only works in the US). That data is converted into an HTML page, which is poured into a WebKit widget for display. Rebuilding this demo using a Listview is left as an exercise for the reader. Also, since this sample is relatively long, we will only show

relevant pieces of the Java code here in this chapter, though you can always download the full source from the CommonsWare Web site.

We retrieve the National Weather Service data every time the activity pops back to the foreground by implementing onResume () in the activity:

(^Override public void onResume() { super.onResume();

Location loc=getLocation();

String url=String.format(format, loc.getLatitude(), loc.getLongitude()); GetMethod method=new GetMethod(url);

int statusCode=client.executeMethod(method);

if (statusCode!=HttpStatus.SC_OK) { Toast .makeText(this,

"Request failed: "+method.getStatusLine(), 2000) .show();

buildForecasts(method.getResponseBodyAsStream()); browser.loadData(generatePage(), "text/html", "UTF-8");

catch (Throwable t) { Toast

.makeText(this, "Request failed: "+t.toString(), 2000) .show();

finally {


First, we retrieve our location using a private getLocation() method, which uses Android's built-in location services - more on this in a later chapter. For now, all you need to know is that Location sports getLatitude() and getLongitude() methods that return the latitude and longitude of the device's position, respectively.

We hold the URL to the National Weather Service XML in a string resource, and pour in the latitude and longitude at runtime. Given our HttpClient

instance created in onCreate(), we populate a GetMethod with that customized URL, then execute that method. If we get 200 as the result code, we build the forecast HTML page (see below) and pour that into the WebKit widget. If we get some other response back, or if the HttpClient blows up with an exception, we provide that error as a Toast, before eventually releasing our HTTP connection for this request.

Self Publishing

Self Publishing

Have you always wanted to write your own book and get it published? Discover How to Write, Print Sell Your Own Book! Have you always wanted to write your own book and get it published? If you have written a book or even if you have a yen to be a writer, you are probably already aware of the competition in the writing field.

Get My Free Ebook

Post a comment