O'Reilly logo

RESTful Java with JAX-RS 2.0, 2nd Edition by Bill Burke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 heavyweight. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required