Книга: Beginning Android

HTTP Operations via Apache HttpComponents

HTTP Operations via Apache HttpComponents

The HTTPClient component of HttpComponents handles all HTTP requests on your behalf. The first step to using HttpClient is, not surprisingly, to create an HttpClient object. Since HttpClient is an interface, you will need to actually instantiate some implementation of that interface, such as DefaultHttpClient.

Those requests are bundled up into HttpRequest instances, with different HttpRequest implementations for each different HTTP verb (e.g., HttpGet for HTTP GET requests). You create an HttpRequest implementation instance, fill in the URL to retrieve and other configuration data (e.g., form values if you are doing an HTTP POST via HttpPost), then pass the method to the client to actually make the HTTP request via execute().

What happens at this point can be as simple or as complicated as you want. You can get an HttpResponse object back, with response code (e.g., 200 for OK), HTTP headers, and the like. Or, you can use a flavor of execute() that takes a ResponseHandler<String> as a parameter — the net result there being that execute() returns just the String representation of the request body. In practice, this is not a recommended approach, because you really should be checking your HTTP response codes for errors. However, for trivial applications, like book examples, the ResponseHandler<String> approach works just fine.

For example, let’s take a look at the Internet/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.[29]

To make this a bit more interesting, we use the Android location services to figure out where we are… sort of. The full details of how that works is described in Chapter 33.

In the onResume() method, we toggle on location updates, so we will be informed where we are now and when we move a significant distance (10km). When a location is available — either at the start or based on movement — we retrieve the National Weather Service data via our updateForecast() method:

private void updateForecast(Location loc) {
 String url = String.format(format, loc.getLatitude(), loc.getLongitude());
 HttpGet getMethod = new HttpGet(url);
 try {
  ResponseHandler<String> responseHandler = new BasicResponseHandler();
  String responseBody = client.execute(getMethod, responseHandler);
  buildForecasts(responseBody);
  String page = generatePage();
  browser.loadDataWithBaseURL(null, page, "text/html",
   "UTF-8", null);
 } catch (Throwable t) {
  Toast.makeText(this, "Request failed: " + t.toString(), 4000).show();
 }
}

The updateForecast() method takes a Location as a parameter, obtained from the location update process. 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 object created in onCreate(), we populate an HttpGet with that customized URL, then execute that method. Given the resulting XML from the REST service, we build the forecast HTML page (see “Parsing Responses”) and pour that into the WebKit widget. If the HttpClient blows up with an exception, we provide that error as a Toast.

Оглавление книги


Генерация: 0.466. Запросов К БД/Cache: 3 / 1
поделиться
Вверх Вниз