Advertise with us

Search Mastertheboss

Our eBooks

JAX-RS client API tutorial

Jakarta EE includes a fluent, request building API for JAX-RS Clients. WildFly application server uses RESTEasy as JAX-RS implementation therefore in this tutorial we will learn how to code a JAX-RS Client from a simple JUnit test example:

@Test
public void testSimple() {
                Client client = ClientBuilder.newClient();
                String hello = client
                        .target(BASE_URL+"/simple/text")
                               .request()
                               .get(String.class);
                assertEquals("hello world!",hello);
}

In the above snippet, the javax.ws.rs.client.Client interface is in charge to manage and configure HTTP connections towards REST services. Behind the scenes, this interface creates a javax.ws.rs.client.WebTarget object, which represents a specific URI. The WebTarget object is hidden by the fluent API used in this example.

We then build the client request by invoking the request method of the WebTarget class and chaining the request with the get method that obviously issues an HTTP GET. The Java type contained in the response Entity is specified as the parameter to the invoked method (In this example a String). Creating and disposing a new Client is a costly task in terms of input/output. Mind to reuse it across your invocations.

One advantage of using JAX-RS Client technology is that you stream Java objects in and out of your service. For example, suppose we have the following method on our ParamRESTService that consumes an XML message containing in it a marshalled SimpleProperty object:

@POST
@Path("/add")
@Consumes(MediaType.APPLICATION_XML)
public Response createPropertyFromXml(SimpleProperty p) {
        int n = ejb.addToList(p);
        return Response.ok("Success").build();
}

By using the JAX-RS client API, it’s simple to consume our service by posting a SimpleProperty object, minding to set the MediaType to XML as shown here:

@Test
public void testParam() {
        Client client = ClientBuilder.newClient();
        SimpleProperty p1 = new SimpleProperty("mykey","value");
        WebTarget myResource = client.target(BASE_URL+"/param/add");
        Response rs = myResource.request(MediaType.APPLICATION_XML)
                                                .post(Entity.xml(p1), Response.class);
        assertEquals(rs.getStatus(),200);
        String out = rs.readEntity(String.class);
        assertEquals(out,"Success");
       //. . . . .
}

Just after the POST to our REST service, we can collect the Response object and inspect its status. The Response object is tested to see if the status is 200 (which means that the request has succeeded). Once inserted our Entity object, we might add another request to query for our Entity. The following block continues our test using the resolveTemplate method to include a Path expression in the request:

SimpleProperty p2 = client.target(BASE_URL + "/param/xml/{id}")
                .resolveTemplate("id", "0")
                .request(MediaType.APPLICATION_XML)
                     .get(SimpleProperty.class);

assertEquals("mykey",p2.getKey());
assertEquals("value",p2.getValue());

Compiling and Running the Test example

In order to run our JUnit test, we need obviously to include the JUnit dependency:

<dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <scope>test</scope>
</dependency>

Additionally, a couple of other dependencies need to be set:

<dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-client</artifactId>
        <scope>test</scope>
</dependency>

<dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxb-provider</artifactId>
        <scope>test</scope>
</dependency>

The first one (resteasy-client) needs to be explicitly to use the ClientBuilder API, the second one (resteasy-jaxb-provider) is needed just if you want RESTEasy API to do String marshaling/unmarshalling of your Entity objects in XML.

In order to run our test, at first make sure you have available the server application (we need to defer testing until the application has been actually deployed)

$ mvn clean install wildfly:deploy -DskipTests=true

Now you can execute your test client by launching:

$ mvn test

You can check the source code for this tutorial at: https://github.com/fmarchioni/practical-enterprise-development/tree/master/code/jaxrs/ee-rest-client

© 2020 mastertheboss.com. All Rights Reserved.

Please publish modules in offcanvas position.