Overview of Jersey JAX-RS Client API

In this post, we will learn some basic steps to write Jersey JAX RS Client API.
Below standard steps to write Jersey JAX RS Client API:
1. Dependencies to use Jersey JAX-RS Client support
2. Creating and configuring a Client instance
3. Targeting a web resource
4. Identifying resource on WebTarget
5. Invoking an HTTP request
6. Complete Example
7. Conclusion

1. Dependencies to use Jersey JAX-RS Client support

Add below dependencies when using the Jersey JAX-RS Client support
<!-- Required only when you are using JAX-RS Client -->
<dependency>
 <groupId>org.glassfish.jersey.core</groupId>
 <artifactId>jersey-client</artifactId>
 <version>2.27</version>
</dependency>

2. Creating and configuring a Client instance

To utilize the client API it is first necessary to build an instance of a Client using one of the static ClientBuilder factory methods. Here's the most simple example:
Client client = ClientBuilder.newClient();
A Client instance can be configured during creation by passing a ClientConfig to the newClient(Configurable) ClientBuilder factory method.
Example: shows a registration of custom client filters
ClientConfig clientConfig = new ClientConfig();
clientConfig.register(MyClientResponseFilter.class);
clientConfig.register(new AnotherClientFilter());
Client client = ClientBuilder.newClient(clientConfig);
In the example, filters are registered using the ClientConfig.register(...) method.

3. Targeting a web resource

Once you have a Client instance you can create a WebTarget from it.
WebTarget webTarget = client.target("http://example.com/rest");
A Client contains several target(...) methods that allow for the creation of WebTarget instance. In this case, we're using target(String URI) version. The uri passed to the method as a String is the URI of the targeted web resource. In more complex scenarios it could be the context root URI of the whole RESTful application, from which WebTarget instances representing individual resource targets can be derived and individually configured. This is possible because JAX-RS WebTarget also implements Configurable:
WebTarget webTarget = client.target("http://example.com/rest");
webTarget.register(FilterForExampleCom.class);

4. Identifying resource on WebTarget

Let's assume we have a webTarget pointing at http://localhost:8080/jersey-crud-example/api URI that represents a context root of a RESTful application and there is a resource exposed on the URI http://localhost:8080/jersey-crud-example/api/users. As already mentioned, a WebTarget instance can be used to derive other web targets. Use the following code to define a path to the resource.
@Path("/users")
public class UserResource {
}
WebTarget resourceWebTarget = webTarget.path("users");
Let's say there is a sub-resource on the path "http://example.com/rest/resource/helloworld". You can derive a WebTarget for this resource simply by:
WebTarget helloworldWebTarget = resourceWebTarget.path("helloworld");
Let's assume that the HelloWorld resource accepts a query param for GET requests which defines the greeting message. The next code snippet shows a code that creates a new WebTarget with the query param defined.
WebTarget helloworldWebTargetWithQueryParam =
        helloworldWebTarget.queryParam("greeting", "Hi World!");

5. Invoking an HTTP request

Let's now focus on invoking a GET HTTP request on the created web targets. To start building a new HTTP request invocation, we need to create a new Invocation.Builder.
Invocation.Builder invocationBuilder =
        helloworldWebTargetWithQueryParam.request(MediaType.TEXT_PLAIN_TYPE);
invocationBuilder.header("some-header", "true");
Invoke GET request on invocationBuilder instance:
Response response = invocationBuilder.get();
Now we can observe the returned response:
System.out.println(response.getStatus());
System.out.println(response.readEntity(String.class));
Invoke POSTrequest on invocationBuilder instance:
Response postResponse =
        helloworldWebTarget.request(MediaType.TEXT_PLAIN_TYPE)
                .post(Entity.entity("A string entity to be POSTed", MediaType.TEXT_PLAIN));

6. Example summary

The following code puts together the pieces used in the earlier examples.
ClientConfig clientConfig = new ClientConfig();
clientConfig.register(MyClientResponseFilter.class);
clientConfig.register(new AnotherClientFilter());
 
Client client = ClientBuilder.newClient(clientConfig);
client.register(ThirdClientFilter.class);
 
WebTarget webTarget = client.target("http://example.com/rest");
webTarget.register(FilterForExampleCom.class);
WebTarget resourceWebTarget = webTarget.path("resource");
WebTarget helloworldWebTarget = resourceWebTarget.path("helloworld");
WebTarget helloworldWebTargetWithQueryParam =
        helloworldWebTarget.queryParam("greeting", "Hi World!");
 
Invocation.Builder invocationBuilder =
        helloworldWebTargetWithQueryParam.request(MediaType.TEXT_PLAIN_TYPE);
invocationBuilder.header("some-header", "true");
 
Response response = invocationBuilder.get();
System.out.println(response.getStatus());
System.out.println(response.readEntity(String.class));
The above code can be refactored fluently
Client client = ClientBuilder.newClient(new ClientConfig()
            .register(MyClientResponseFilter.class)
            .register(new AnotherClientFilter()));
 
String entity = client.target("http://example.com/rest")
            .register(FilterForExampleCom.class)
            .path("resource/helloworld")
            .queryParam("greeting", "Hi World!")
            .request(MediaType.TEXT_PLAIN_TYPE)
            .header("some-header", "true")
            .get(String.class);
Here is another a very simple GET request returning a String representation (entity):
String responseEntity = ClientBuilder.newClient()
            .target("http://example.com").path("resource/rest")
                        .request().get(String.class);

Conclusion

This post gives the overview of Jersey JAX-RS Client API and steps to create Jersey JAX-RS Client for Jersey Restful web services.
You can learn more about jersey on Jersey Rest Developer Guide
All the code of this article is available over on Github. This is a Maven-based project, so it should be easy to import and run as it is.

Comments