Chapter 16. Alternative Java Clients
While JAX-RS 2.0 added client support, there are other Java clients you can use to interact with web services if you do not have JAX-RS 2.0 available in your environment.
java.net.URL
Like most programming languages, Java has a built-in HTTP client library. It’s nothing fancy, but it’s good enough to perform most of the basic functions you need. The API is built around two classes, java.net.URL
and java.net.HttpURLConnection
. The URL
class is just a Java representation of a URL. Here are some of the pertinent constructors and methods:
public
class
URL
{
public
URL
(
java
.
lang
.
String
s
)
throws
java
.
net
.
MalformedURLException
{}
public
java
.
net
.
URLConnection
openConnection
()
throws
java
.
io
.
IOException
{}
...
}
From a URL
, you can create an HttpURLConnection
that allows you to invoke specific requests. Here’s an example of doing a simple GET request:
URL
url
=
new
URL
(
"http://example.com/customers/1"
);
connection
=
(
HttpURLConnection
)
url
.
openConnection
();
connection
.
setRequestMethod
(
"GET"
);
connection
.
setRequestProperty
(
"Accept"
,
"application/xml"
);
if
(
connection
.
getResponseCode
()
!=
200
)
{
throw
new
RuntimeException
(
"Operation failed: "
+
connection
.
getResponseCode
());
}
System
.
out
.
println
(
"Content-Type: "
+
connection
.
getContentType
());
BufferedReader
reader
=
new
BufferedReader
(
new
InputStreamReader
(
connection
.
getInputStream
()));
String
line
=
reader
.
readLine
();
while
(
line
!=
null
)
{
System
.
out
.
println
(
line
);
line
=
reader
.
readLine
();
}
connection ...
Get RESTful Java with JAX-RS 2.0, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.