The JAX-RS Client API

JAX-RS, Restlet, and the JAX-WS @WebServiceProvider frameworks for RESTful services include client-side APIs. These APIs are meant to simplify the task of writing RESTful clients in general, not just clients against a RESTful service implemented in a particular framework. To underscore the point, this section takes a look at the JAX-RS client-side API (see Example 3-18); the client, however, goes against the servlet-based predictions2 RESTful service from Chapter 2.

Example 3-18. A sample client using the JAX-RS client-side API

package jerseyClient;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.representation.Form;

public class JerseyClient {
    private static final String baseUrl = "http://localhost:8080/predictions2";

    public static void main(String[ ] args) {
        new JerseyClient().demo();
    }
    private void demo() {
        Client client = Client.create();
        client.setFollowRedirects(true); // in case the service redirects
        WebResource resource = client.resource(baseUrl);
        getAllDemo(resource);
        postDemo(resource); // same resource but different verb
        String url = baseUrl + "?id=32";
        resource = client.resource(url);
        getOneDemo(resource);
        deleteDemo(resource); // delete id = 32
    }
    private void getAllDemo(WebResource resource) {
        // GET all XML
        String response =
            resource.accept(MediaType.APPLICATION_XML_TYPE).get(String.class);
        report("GET all in XML:\n", response);
        // GET all JSON
        

Get Java Web Services: Up and Running, 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.