This tutorial covers how to develop some Java REST client examples using OkHttp, an HTTP & HTTP/2 client for Android and Java applications.
1. Preparation
Let’s assume that we have an RESTful web service with several API as below. And we’re going to use OkHttp client to create several basic Java REST client examples which will communicate with this RESTful web service.
Assume that we have an RESTful web services with several API 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 or you can download it here: Java-Examples.zip
Let’s define a POJO to map with the Book response as below:
1 2 3 4 5 6 |
public class Book { private Long id; private String name; private String author; // All getters and setters } |
We use OkHttp client to communicate with the RESTful service above and we use Jackson to convert JSON responses to Java objects and vice versa.
1 2 3 4 5 6 7 8 9 10 |
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.5</version> </dependency> |
2. Java REST client examples using OkHttp
In this section, we’re going to use OkHttp library to create, update, query, and delete resources from REST API.
2.1. Make a HTTP GET request to the RESTful web service (Get all books)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class BookRepositoryImplOkHttp { private static final String URI_BOOK = "http://localhost:8080/v1/books"; public Book[] getAllBooks() throws Exception { Book[] books = null; // create new client OkHttpClient httpclient = new OkHttpClient(); Request request = new Request.Builder().url(URI_BOOK).get().build(); try (Response response = httpclient.newCall(request).execute()) { // converts response into an array of books ObjectMapper mapper = new ObjectMapper(); books = mapper.readValue(response.body().bytes(), Book[].class); } return books; } } |
2.2. Make a HTTP POST request to the RESTful web service (create a book)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public class BookRepositoryImplOkHttp { private static final MediaType MediaTypeJSON = MediaType .parse("application/json; charset=utf-8"); private static final String URI_BOOK = "http://localhost:8080/v1/books"; public Book createBook(Book book) throws Exception { Book createdBook = null; // creates new client OkHttpClient httpclient = new OkHttpClient(); // convert the book to JSON by Jackson ObjectMapper mapper = new ObjectMapper(); String jsonBook = mapper.writeValueAsString(book); // build a request Request request = new Request.Builder().url(URI_BOOK) .post(RequestBody.create(MediaTypeJSON, jsonBook)).build(); try (Response response = httpclient.newCall(request).execute()) { if (response.isSuccessful()) { // Get back the response and convert it to a Book object createdBook = mapper.readValue(response.body().bytes(), Book.class); } } return createdBook; } } |
2.3. Make a HTTP PUT request to the RESTful web service (Update a book)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public class BookRepositoryImplOkHttp { private static final MediaType MediaTypeJSON = MediaType .parse("application/json; charset=utf-8"); private static final String URI_BOOK = "http://localhost:8080/v1/books"; public Book updateBook(Book book) throws Exception { Book updatedBook = null; OkHttpClient httpclient = new OkHttpClient(); //converts the book to JSON first ObjectMapper mapper = new ObjectMapper(); String jsonBook = mapper.writeValueAsString(book); Request request = new Request.Builder().url(URI_BOOK + "/" + book.getId()) .put(RequestBody.create(MediaTypeJSON, jsonBook)).build(); try (Response response = httpclient.newCall(request).execute()) { if (response.isSuccessful()) { // convert the reponse into a Book object updatedBook = mapper.readValue(response.body().bytes(), Book.class); } } return updatedBook; } } |
2.4. Make a HTTP DELETE request to the RESTful web service (delete a book)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class BookRepositoryImplOkHttp { private static final MediaType MediaTypeJSON = MediaType .parse("application/json; charset=utf-8"); private static final String URI_BOOK = "http://localhost:8080/v1/books"; public void deleteBook(Long id) throws Exception { OkHttpClient httpclient = new OkHttpClient(); Request request = new Request.Builder().url(URI_BOOK + "/" + id).delete().build(); try (Response response = httpclient.newCall(request).execute()) { if (!response.isSuccessful()) { throw new RuntimeException("Failed to delete book with id:" + id); } } } } |
4. Conclusions
We have just implemented several Java REST client examples using OkHttp library, an HTTP & HTTP/2 client for Android and Java applications powered by Square. OkHttp is introduced as a very efficiency Http client with HTTP/2 support or connection pooling reduces request latency, etc. In future posts, we will explore more feature of this library. Meanwhile, there are other tutorials related to the Java REST client for your references:
Java REST Client Example With Retrofit 2
Java REST Client Using Netflix Feign
Java REST Client Using Apache HttpClient
Java REST Client Using Spring RestTemplate
Java REST Client With 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
Basic Authentication with OkHttp Example
WebSocket Client Example with OkHttp
How to Cache Response with OkHttp