Chapter 8. JAX-RS Client API

One huge gaping hole in the first version of the JAX-RS specification was the lack of a client API. You could slog through the very difficult-to-use java.net.URL set of classes to invoke on remote RESTful services. Or you could use something like Apache HTTP Client, which is not JAX-RS aware, so you would have to do marshalling and unmarshalling of Java objects manually. Finally, you could opt to use one of the proprietary client APIs of one of the many JAX-RS implementations out there. This would, of course, lock you into that vendor’s implementation. JAX-RS 2.0 fixed this problem by introducing a new HTTP client API.

Client Introduction

Before I dive into the Client API, let’s look at a simple code example that illustrates the basics of the API:

Client client = ClientBuilder.newClient();

WebTarget target = client.target("http://commerce.com/customers");

Response response = target.post(Entity.xml(new Customer("Bill", "Burke)));
response.close();

Customer customer = target.queryParam("name", "Bill Burke")
                          .request()
                          .get(Customer.class);
client.close();

This example invokes GET and POST requests on a target URL to create and view a Customer object that is represented by XML over the wire. Let’s now pull this code apart and examine each of its components in detail.

Bootstrapping with ClientBuilder

The javax.ws.rs.client.Client interface is the main entry point into the JAX-RS Client API. Client instances manage client socket connections and are pretty ...

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.