Jersey is the Reference Implementation of JAX-RS. The Jersey Client API is an easy-to-use and high-level Java API that can help you write clients for any HTTP-based RESTful Web service.
This section will create a client that will access the RESTful resource published at the /customers/{id} path.
public static void main(String[] args) {
String BASE_URL = "http://localhost:8080/JavaEE6SampleApp/restful/customers/";
Client client = Client.create();
WebResource resource = client.resource(BASE_URL + "1");
resource.addFilter(new LoggingFilter());
resource.get(String.class);
resource.accept(MediaType.APPLICATION_JSON).get(String.class);
}
Notice the following points:
- This code creates a new Jersey client runtime instance. This is an expensive object and so must be saved if no other configuration is required to access the resources.
- A new WebResource is created per RESTful resource that is capable of building requests to send to the resource and processing responses returned from the resource. Each WebResource follows a builder pattern to specify the required MIME type in the response, application/json in this case.
- A LoggingFilter is added to the resource to print the request and response messages.
- The code then requests a default and JSON representation of the resource in two separate calls.
Fix the imports by taking all the defaults.
The output shows request and response messages to/from the resource. The first pair of messages is pre-fixed with “1” and shows the default XML response coming back. The second pair of messages is pre-fixed with “2” and shows the “Accept” header going from client to endpoint for content-negotiation with server. The server understands the expected format and returns a JSON response.