Java™ API for RESTful Web Services (JAX-RS) provides Client API for accessing web resources. In this article, we will talk about the basic concepts of the Client API. After reading, you will understand:
- Maven dependencies when using Jersey as JAX-RS client
- Create a Client instance
- Create a WebTarget instance
- Consume a HTTP response
The Java classes introduced in this article are principally defined
javax.ws.rs.client. I’m using Jersey, the reference implementation
of JAX-RS for the examples.
In order to use Jersey as JAX-RS client, you need to add the following
dependency in your POM (
Create Client Instance
An instance of
Client is required to access a Web resource using the Client
API. The default instance of
Client can be obtained by calling
Client instances can be configured using methods inherited
Configurable as follows:
Create WebTarget Instance
Client#target(...) method can create a
They accept String, URI, URI Builder, and Link as input parameter type. For
example, create web target using a String:
Once created, you can use
path to define the path to a specific resource. For
example, if you need to request book 1 defined by the following URL:
You can do:
Conceptually, the steps required to submit a request are the following: 1.
obtain an instance of
Client; 2. create a
WebTarget; 3. create a request
WebTarget; 4. submit a request or get a prepared
later submission. JAX-RS uses method chaining to support different
configurations, such as setting headers, cookies, query parameters, etc.
Consume HTTP Response
Once the HTTP response is obtained as class
javax.ws.rs.core.Response, you can
get the HTTP status, read the entity, get the MIME type, cookie, etc.
In this article, we’ve seen how to create a Client and WebTarget using Jersey Client API, in particular the method chaining techniques for setting different parts of a HTTP request. We’ve also seen how to get information from the HTTP response. Hope you enjoy this article, see you the next time!