Java Reference
In-Depth Information
// Get a customer
Customer cust
=
customerProxy
.
getCustomer
(
333
);
// Update a customer
cust
.
setName
(
"burke"
);
customerProxy
.
updateCustomer
(
333
,
cust
);
When you invoke one of the methods of the returned
CustomerResource
proxy, it converts
the Java method call into an HTTP request to the server using the metadata defined in the an-
notations applied to the
CustomerResource
interface. For example, the
getCustomer()
in-
vocation in the example code knows that it must do a GET request on the
ht-
tp://example.com/customers/333
URI, because it has introspected the values of the
@Path
,
@GET
, and
@PathParam
annotations on the method. It knows that it should be getting back
XML from the
@Produces
annotation. It also knows that it should unmarshal it using a
JAXB
MessageBodyReader
, because the
getCustomer()
method returns a JAXB annotated
class.
Advantages and Disadvantages
A nice side effect of writing Java clients with this proxy framework is that you can use the
Java interface for Java clients and JAX-RS services. With one Java interface, you also have a
nice, clear way of documenting how to interact with your RESTful Java service. As you can
see from the example code, it also cuts down on a lot of boilerplate code. The disadvantage,
of course, is that this framework, while open source, is proprietary.
Wrapping Up
In this chapter, you learned three alternative ways to write RESTful clients in Java using the
JDK's
java.net.HttpURLConnection
class, Apache HttpClient, and the RESTEasy Client
Proxy Framework. All three have their merits as alternatives to the JAX-RS 2.0 Client API.
[
20
]
For more information, see
http://hc.apache.org
.