Java Reference
In-Depth Information
REST Web Service Client
Problem
You need to read from a URL (e.g., connect to a RESTful web service).
Solution
Use the standard
URLConnection
or the third-party Apache
HttpClient
library.
This technique applies anytime you need to read from a URL, not just a RESTful web ser-
vice.
Discussion
Although the Apache
HttpClient
library gives you more flexibility, for most simple REST
web services it is overkill. All we usually need is the ability to open and read from a URL.
As our simple example, we'll use the free, open source
freegeoip.net
service. IP
GeoLocation refers to finding the geographic location (geolocation) of a given IP connection,
usually the address of a client or server (or its IP proxy, if it is behind a proxy).
The FreeGeoIP service supports three different output formats: CSV (see
Parsing Comma-
Separated Data
)
, JSON (see
Chapter 19
)
, and XML (see
Chapter 20
)
. As is typical of REST
services that offer multiple formats, you choose your format simply by putting it as part of
the URL. The service's documentation states that its URL usage is just:
http://freegeoip.net/{format}/{host}
The protocol can be either HTTP or HTTPS. The
format
can be
csv
,
json
, or
xml
(all
lowercase). The “host” is optional: if not given, the IP address from which you are connect-
ing will be looked up; if given, the host may be specified as a numeric IP or a resolvable
hostname.
Here is the code:
public
public class
class
RestClientFreeGeoIp
RestClientFreeGeoIp
{
public
public static
static
void
void
main
(
String
[]
args
)
throws
throws
Exception
{
URLConnection conn
=
new
new
URL
(
"http://freegeoip.net/json/www.oreilly.com"
)