Partner – Payara – NPI (cat=Jakarta EE)
announcement - icon

Can Jakarta EE be used to develop microservices? The answer is a resounding ‘yes’!

>> Demystifying Microservices for Jakarta EE & Java EE Developers

Course – LS (cat=REST)

Get started with Spring and Spring Boot, through the reference Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

Jersey is an open source framework for developing RESTFul Web Services. It also has great inbuilt client capabilities.

In this quick tutorial, we will explore the creation of JAX-RS client using Jersey 2.

For a discussion on the creation of RESTful Web Services using Jersey, please refer to this article.

Further reading:

REST API with Jersey and Spring

Building Restful Web Services using Jersey 2 and Spring.

CORS in JAX-RS

Learn how to implement Cross-Origin Resource Sharing (CORS) mechanism in JAX-RS based applications.

Jersey Filters and Interceptors

Take a look at how filters and interceptors work in the Jersey framework.

2. Maven Dependencies

Let’s begin by adding the required dependencies (for Jersey JAX-RS client) in the pom.xml:

<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-client</artifactId>
    <version>2.25.1</version>
</dependency>

To use Jackson 2.x as JSON provider:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.25.1</version>
</dependency>

The latest version of these dependencies can be found at jersey-client and jersey-media-json-jackson.

3. RESTFul Client in Jersey

We will develop a JAX-RS client to consume the JSON and XML REST APIs that we developed here (we need to make sure that the service is deployed and the URL is accessible).

3.1. Resource Representation Class

Let’s have a look at the resource representation class:

@XmlRootElement
public class Employee {
    private int id;
    private String firstName;

    // standard getters and setters
}

JAXB annotations like @XmlRootElement are required only if XML support is needed.

3.2. Creating an Instance of a Client

The first thing we need is an instance of a Client:

Client client = ClientBuilder.newClient();

3.3. Creating a WebTarget

Once we have the Client instance, we can create a WebTarget using the URI of the targeted web resource:

WebTarget webTarget 
  = client.target("http://localhost:8082/spring-jersey");

Using WebTarget, we can define a path to a specific resource:

WebTarget employeeWebTarget 
  = webTarget.path("resources/employees");

3.4. Building an HTTP Request Invocation

An invocation builder instance is created one of the WebTarget.request() methods:

Invocation.Builder invocationBuilder 
  = employeeWebTarget.request(MediaType.APPLICATION_JSON);

For XML format, MediaType.APPLICATION_XML can be used.

3.5. Invoking HTTP Requests

Invoking HTTP GET:

Response response 
  = invocationBuilder.get(Employee.class);

Invoking HTTP POST:

Response response 
  = invocationBuilder
  .post(Entity.entity(employee, MediaType.APPLICATION_JSON);

3.6. Sample REST Client

Let’s begin writing a simple REST client. The getJsonEmployee() method retrieves an Employee object based on the employee id. The JSON returned by the REST Web Service is deserialized to the Employee object before returning.

Using the JAX-RS API fluently to create web target, invocation builder and invoking a GET HTTP request:

public class RestClient {
 
    private static final String REST_URI 
      = "http://localhost:8082/spring-jersey/resources/employees";
 
    private Client client = ClientBuilder.newClient();

    public Employee getJsonEmployee(int id) {
        return client
          .target(REST_URI)
          .path(String.valueOf(id))
          .request(MediaType.APPLICATION_JSON)
          .get(Employee.class);
    }
    //...
}

Let’s now add a method for POST HTTP request. The createJsonEmployee() method creates an Employee by invoking the REST Web Service for Employee creation. The client API internally serializes the Employee object to JSON before invoking the HTTP POST method:

public Response createJsonEmployee(Employee emp) {
    return client
      .target(REST_URI)
      .request(MediaType.APPLICATION_JSON)
      .post(Entity.entity(emp, MediaType.APPLICATION_JSON));
}

4. Testing the Client

Let’s test our client with JUnit:

public class JerseyClientLiveTest {
 
    public static final int HTTP_CREATED = 201;
    private RestClient client = new RestClient();

    @Test
    public void givenCorrectObject_whenCorrectJsonRequest_thenResponseCodeCreated() {
        Employee emp = new Employee(6, "Johny");

        Response response = client.createJsonEmployee(emp);

        assertEquals(response.getStatus(), HTTP_CREATED);
    }
}

5. Conclusion

In this article, we have introduced JAX-RS client using Jersey 2 and developed a simple RESTFul Java client.

As always, the full source code is available in this Github project.

Course – LS (cat=REST)

Get started with Spring and Spring Boot, through the Learn Spring course :

>> CHECK OUT THE COURSE
res – REST (eBook) (cat=REST)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.