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 object. Since is an interface, you will need to actually instantiate some implementation of that interface, such as .

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

What happens at this point can be as simple or as complicated as you want. You can get an object back, with response code (e.g., 200 for OK), HTTP headers, and the like. Or, you can use a flavor of that takes a as a parameter – the net result there being that returns just the 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 approach works just fine.

For example, let’s take a look at the 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 widget for display. Rebuilding this demo using a 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.[25]

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 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 method:

Дата добавления: 2015-05-16; просмотров: 511; ЗАКАЗАТЬ НАПИСАНИЕ РАБОТЫ

Поиск по сайту:

При помощи поиска вы сможете найти нужную вам информацию, введите в поисковое поле ключевые слова и изучайте нужную вам информацию.

Поделитесь с друзьями:

Если вам понравился данный ресурс вы можете рассказать о нем друзьям. Сделать это можно через соц. кнопки выше. - Хелпикс.Орг - 2014-2020 год. Материал сайта представляется для ознакомительного и учебного использования. | Поддержка
Генерация страницы за: 0.005 сек.