Developing a RESTful web service client

Although curl allows us to quickly test our RESTful web services and it is a developer-friendly tool, it is not exactly user-friendly; we shouldn't expect to have our user enter curl commands in their command line to use our web service. For this reason, we need to develop a client for our services. JAX-RS includes a standard client-side API that we can use to easily develop RESTful web service clients.

The following example illustrates how to use the JAX-RS client API:

package com.ensode.javaee8book..jaxrsintroclient; 
 
import com.ensode.jaxbxmlconversion.entity.Customer; 
import javax.ws.rs.client.Client; 
import javax.ws.rs.client.ClientBuilder; 
import javax.ws.rs.client.Entity; 
 
public class App { 
 
    public static void main(String[] args) { 
        App app = new App(); 
        app.insertCustomer(); 
    } 
 
    public void insertCustomer() { 
        Customer customer = new Customer(234L, "Tamara", "A", 
                "Graystone"); 
        Client client = ClientBuilder.newClient();                 
client.target(

"http://localhost:8080/jaxbxmlconversion/resources/customer").

request().put(

Entity.entity(customer, "text/xml"),

Customer.class);
} }

The first thing we need to do is create an instance of javax.ws.rs.client.Client by invoking the static newClient() method on the javax.ws.rs.client.ClientBuilder class.

We then invoke the target() method on our Client instance, passing the URI of our RESTful web service as a parameter. The target() method returns an instance of a class implementing the javax.ws.rs.client.WebTarget interface.

At this point, we invoke the request() method on our WebTarget instance. This method returns an implementation of the javax.ws.rs.client.Invocation.Builder interface.

In this particular example, we are sending an HTTP PUT request to our RESTful web service, therefore, at this point, we invoke the put() method of our Invocation.Builder implementation. The first parameter of the put() method is an instance of javax.ws.rs.client.Entity . We can create one on the fly by invoking the static entity() method on the Entity class. The first parameter for this method is the object we wish to pass to our RESTful web service, and the second parameter is the string representation of the MIME type of the data we will be passing to the RESTful web service. The second parameter of the put() method is the type of response the client expects from the service. After we invoke the put() method, an HTTP PUT request is sent to our RESTful web service and the method we decorated with the @Put annotation ( createCustomer(), in our example) is invoked. There are similar get(), post(), and delete() methods which we can invoke to send the corresponding HTTP requests to our RESTful web service.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.85.221