Unirest is lightweight HTTP request client libraries available in multiple languages including Java, .NET, Ruby, Node, Objective-C, etc. Like other REST client libraries, Unirest aims to simplify making HTTP REST requests. In this tutorial, I’d like to share how to implement Java REST client using Unirest Java API.
1. Preparation
Assume that we have a REST API with several APIs as below:
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 can not delete the book.
1.5 Source code
The demo source code can be found on the Github.
We will use Unirest Java API to communicate with above REST API. The dependencies we need directly in the pom file is:
1 2 3 4 5 |
<dependency> <groupId>com.mashape.unirest</groupId> <artifactId>unirest-java</artifactId> <version>1.4.9</version> </dependency> |
2. Create Java REST Client Using Unirest Java API.
2.1. Serialization
As required from the above REST API, the request and response should be in JSON. Therefore, we may want a way to serialize our Java object into JSON when we send request to the service and deserialize the response to the Java objects automatically. To do that in Unirest Java API, we just need to set an the ObjectMapper it as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public BookRepositoryImplUnirest() { Unirest.setObjectMapper(new ObjectMapper() { private com.fasterxml.jackson.databind.ObjectMapper jacksonObjectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); public <T> T readValue(String value, Class<T> valueType) { try { return jacksonObjectMapper.readValue(value, valueType); } catch (IOException e) { throw new RuntimeException(e); } } public String writeValue(Object value) { try { return jacksonObjectMapper.writeValueAsString(value); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }); } |
We have set the Jackson ObjectMapper for the Unirest in the constructor of our class. We just need to do 1 time for all the method calls. After that, we are ready to invoke methods on the Unirest.
2.2. Make a GET request to the RESTful web service (Get all books)
1 2 3 4 5 6 7 8 9 |
public class BookRepositoryImplUnirest { private static final String URI_BOOK = "http://localhost:8080/v1/books"; public Book[] getAllBooks() throws Exception { HttpResponse<Book[]> response = Unirest.get(URI_BOOK).asObject(Book[].class); Book[] books = response.getBody(); return books; } } |
2.3. Make a POST request to the RESTful web service (create a book)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class BookRepositoryImplUnirest { private static final String URI_BOOK = "http://localhost:8080/v1/books"; public Book createBook(Book book) throws Exception { HttpResponse<Book> response = Unirest.post(URI_BOOK).header("accept", "application/json") .header("Content-Type", "application/json").body(book).asObject(Book.class); int status = response.getStatus(); System.out.println("Status code: " + status); Book createdBook = response.getBody(); return createdBook; } } |
We also need to call the asObject method of the Unirest to deserialize the response to a Java object.
2.4. Make a PUT request to the RESTful web service (Update a book)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class BookRepositoryImplUnirest { private static final String URI_BOOK = "http://localhost:8080/v1/books"; public Book updateBook(Book book) throws Exception { HttpResponse<Book> response = Unirest.put(URI_BOOK + "/{id}") .routeParam("id", String.valueOf(book.getId())).header("accept", "application/json") .header("Content-Type", "application/json").body(book).asObject(Book.class); int status = response.getStatus(); System.out.println("Status code: " + status); Book updatedBook = response.getBody(); return updatedBook; } } |
Note that we have just modified the URL of the API to include the book id as the resource path
2.5. Make a DELETE request to the RESTful web service (delete a book)
1 2 3 4 5 6 7 8 9 |
public class BookRepositoryImplUnirest { private static final String URI_BOOK = "http://localhost:8080/v1/books"; public void deleteBook(Long id) throws Exception { HttpResponse<String> response = Unirest.delete(URI_BOOK + "/{id}").routeParam("id", String.valueOf(id)).asString(); System.out.println("Status code:" + response.getStatus()); } } |
3. Conclusion.
We have seen some example about implementing Java REST client using Unirest Java API. In similar to other libraries, Unirest is very lightweight and simple. If you want to learn more about implementing Java REST client using other libraries such as: Netflix Feign, Jersey, Spring RestTemplate, etc, you can refer to following links:
Simple Java REST Client Using java.net.URL package
Java REST Client Using Spring RestTemplate
Java REST Client Using Apache Httpcomponents
Java REST Client Using Jersey Client
Java REST Client Using Resteasy Client
Java REST Client Using Resteasy Client Proxy Framework
Java REST Client Using Apache CXF Proxy-based API
Java REST Client Using Netflix Feign
Set Timeouts with Unirest for Java