This tutorial is going to illustrate how to create a Java REST client using Jersey client API which is a standard Java-based API for communication with RESTful Web services. For more detail information, please visit Jersey official website.
1. Preparation
In this tutorial, we’re going to use Jersey client API to interact with a RESTful web service. Therefore, let’s assume that we have a RESTful web service with several API as follows:
1.1. Get All Books
1 |
GET http://localhost:8080/v1/books |
1.2. Create A New Book
1 |
POST http://localhost:8080/v1/books |
Example:
1 2 3 4 |
{ "name": "Java How To Program", "author": "Paul Deitel" } |
Responses: application/json
Example:
1 2 3 4 5 |
{ "id": 5 "name": "Java How To Program", "author": "Paul Deitel" } |
STATUS 201 if the book is created successfully.
1.3. Update A Book
1 |
PUT http://localhost:8080/v1/books/{id} |
Example:
1 2 3 4 5 |
{ "id": 1, "name": "Java How To Program 2nd", "author": "Paul Deitel" } |
Responses: application/json
STATUS 200 if the book is updated successfully.
STATUS 400 if there is no book with given id.
1.4. Delete A Book
1 |
DELETE http://localhost:8080/v1/books/{id} |
STATUS 204 if the book is deleted successfully.
STATUS 400 if there is no book with given id or cannot delete the book.
1.5. Jersey Library Dependencies
We use Jersey client library for communicating with the RESTful API and its message provider Jersey-media-json-jackson to convert JSON to Java objects.
1 2 3 4 5 6 7 8 9 10 11 |
<dependency> <groupId>org.glassfish.jersey.core</groupId> <artifactId>jersey-client</artifactId> <version>2.26</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-json-jackson</artifactId> <version>2.26</version> </dependency> |
1.6. Sample Source Code
The sample source code presented in this tutorial is available on Github.
2. Create Java REST Client Using Jersey Client Library
Let’s get through some examples of creating Java REST client using Jersey client library. We will query, create, update and delete resources from the above REST service.
2.1. Make a GET request to the RESTful web service (Get all books)
Let’s get to an example where we make an HTTP GET request to retrieve resource information from the RESTful web service:
1 2 3 4 5 6 7 8 9 10 11 12 |
public class BookRepositoryImplJersey { private static final String URI_BOOK = "http://localhost:8080/v1/books"; public Book[] getAllBooks() throws Exception { Client client = ClientBuilder.newClient(); Response response = client.target(URI_BOOK).request().get(); int status = response.getStatus(); System.out.println("Status code: " + status); Book[] books = response.readEntity(Book[].class); return books; } } |
We have created a Jersey client, targeted it with a resource path, build a request and invoke the HTTP GET method for the current request synchronously.
From the above response, we call the method “readEntity” to map the entity stream to an array of books.
And next, let see an example of testing the above method:
1 2 3 4 5 |
public static void main(String[] args) throws Exception { BookRepositoryImplJersey bookRepository = new BookRepositoryImplJersey(); Book books[] = bookRepository.getAllBooks(); System.out.println(books[0]); } |
And the output of the console:
1 2 |
Status code: 200 Book [id=1, name=Java How To Program, author=Paul Deitel] |
2.2. Make a POST request to the RESTful web service (Create a book)
Let’s take a look at an example where we use Jersey client API to make a POST request to the RESTful web service:
1 2 3 4 5 6 7 8 9 10 11 |
public class BookRepositoryImplJersey { private static final String URI_BOOK = "http://localhost:8080/v1/books"; public Book createBook(Book book) { Client client = ClientBuilder.newClient(); Response response = client.target(URI_BOOK).request() .post(Entity.entity(book, MediaType.APPLICATION_JSON_TYPE)); return response.readEntity(Book.class); } } |
Because the RESTful API requires the POST method, we must call the post method on our request object. As for the posted entity, we create a new entity from our book and specify application/json as the MediaType.
Here is our updated main method for testing.
1 2 3 4 5 6 |
public static void main(String[] args) throws Exception { BookRepositoryImplJersey bookRepository = new BookRepositoryImplJersey(); Book book = new Book(null, "Effective Java", "Joshua Bloch"); Book createdBook = bookRepository.createBook(book); System.out.println(createdBook); } |
The output of the console is:
1 2 |
Status code: 201 Book [id=5, name=Effective Java, author=Joshua Bloch] |
The id of the created book is returned, and the status code is 201 which is returned when the book is created successfully.
2.3. Make a PUT request to the RESTful web service (Update a book)
Next, we’re going to make a PUT request to the RESTful web service using Jersey client API:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class BookRepositoryImplJersey { private static final String URI_BOOK = "http://localhost:8080/v1/books"; public Book updateBook(Book book) throws Exception { Client client = ClientBuilder.newClient(); WebTarget target = client.target(URI_BOOK).path(String.valueOf(book.getId())); Response response = target.request(MediaType.APPLICATION_JSON_TYPE) .put(Entity.entity(book, MediaType.APPLICATION_JSON_TYPE)); int status = response.getStatus(); System.out.println("Status code: " + status); Book createdBook = response.readEntity(Book.class); return createdBook; } } |
We have created a Restful web service client, targeted it a resource path, append path(id of the book) to the URI of the current target instance. Then, we build a request, create an entity from our book with the application/json as the MediaType and invoke HTTP PUT method.
The main method to test is updated:
1 2 3 4 5 6 7 8 9 10 11 |
public static void main(String[] args) throws Exception { BookRepositoryImplJersey bookRepository = new BookRepositoryImplJersey(); // Getting the first book from the RESTful service Book book = bookRepository.getAllBooks()[0]; System.out.println(book); // Change the name book.setName(book.getName() + " 3rd"); // Then update the book book = bookRepository.updateBook(book); System.out.println(book); } |
Let’s run the method “main” and see the output printed out:
1 2 3 |
Book [id=1, name=Java How To Program, author=Paul Deitel] Status code: 200 Book [id=1, name=Java How To Program 3rd, author=Paul Deitel] |
2.4. Make a DELETE request to the RESTful web service (Delete a book)
Now, let’s see an example which we make a DELETE request to the RESTful web service using Jersey client API:
1 2 3 4 5 6 7 8 9 10 |
public class BookRepositoryImplJersey { private static final String URI_BOOK = "http://localhost:8080/v1/books"; public void deleteBook(Long id) { Client client = ClientBuilder.newClient(); WebTarget target = client.target(URI_BOOK).path(String.valueOf(id)); Response response = target.request().delete(); System.out.println("Status code:" + response.getStatus()); } } |
We have created a new client, targeted it a resource path, append path(id of the book) to the URI of the current target instance and invoke the delete method.
Here is our updated main method:
1 2 3 4 5 6 7 |
public static void main(String[] args) throws Exception { BookRepositoryImplJersey bookRepository = new BookRepositoryImplJersey(); // Getting the first book from the RESTful service Book book = bookRepository.getAllBooks()[0]; bookRepository.deleteBook(book.getId()); } |
And the output to the console after running the method:
1 |
Status code:204 |
3. Conclusion
We have seen some examples how to create Java REST client using Jersey client API. Like other frameworks, Jersey client API facilitates consuming of RESTful API. If you want to try other examples with other frameworks such as Spring RestTempate, Apache HttpComponent, and even java.net.URL package, you can see my previous posts here:
Java REST Client Examples Using OkHttp
Java REST Client Using Netflix Feign
Java REST Client Example Using Retrofit 2
Simple Java REST Client Using java.net.URL package
Java REST Client Using Spring RestTemplate
Java REST Client Using Apache HttpClient
Java REST Client Using Resteasy Client Proxy Framework
Java REST Client Using Resteasy Client
Very straight forward tutorial. Thank you very much for sharing.