How to Consume REST Web Service (GET/POST) in Java 11 or Above
Learn how to use the standard HTTPClient class as part of java.net.http and to create RestClient, send HTTP GET and POST requests, and handle the JSON response.
Join the DZone community and get the full member experience.
Join For FreeRESTful web services are the de-facto way of integrating first- and third-party services in web and mobile applications. When programming in Java, there are a plethora of options on how to consume REST APIs, however many of them are either out of fashion or too complicated. At my company, we provide developers Java SDK to build on top of our open platform, and the most common operation involves making authenticated web requests to get data from the RingCentral platform.
In this tutorial, we will learn how to use the standard HTTPClient class that comes in JDK 11.0 or later as part of java.net.http. We will use that to create RestClient, send HTTP GET and POST requests with JSON body, and handle the JSON response using the body handler object.
If you are using microservices frameworks such as SpringBoot or Micronaut, they already come with helper libraries to handle REST APIs, however, you can use the standard Java HTTP client library as a replacement if needed.
Key classes that we will use are:
- HttpClient
- HttpRequest
- HttpResponse
In the code snippet below, the first line is used to instantiate the HTTPClient with default configuration which comes with HTTP/2.0 support.
HttpClient client = HttpClient.newHttpClient();
Create HTTPRequest Object using the builder pattern and provide it with the configuration for HTTP GET Request. It is very simple, as shown below:
HttpRequest getRequest = HttpRequest.newBuilder()
.uri(URI.create("http://openjdk.java.net/"))
.build();
Create another HTTPRequest object for making a POST request as shown below. Note that we provide it with additional configuration, most importantly the "file.json" which will consist of the JSON request body.
HttpRequest postRequest = HttpRequest.newBuilder()
.uri(URI.create("http://openjdk.java.net/"))
.timeout(Duration.ofMinutes(1))
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofFile(Paths.get("file.json")))
.build()
In the following code snippet, we are choosing to make an asynchronous HTTP request instead of a synchronous request as it is a preferred approach for web applications so as to not block the client-side application from performing other tasks.
client.sendAsync(getRequest, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
Example with RingCentral Platform:
static HttpResponse<String> getData(String jsonStr, String endpoint, String accessToken) throws Exception {
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest httpRequest = HttpRequest.newBuilder()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + accessToken)
.uri(URI.create("https://platform.devtest.ringcentral.com" + endpoint))
.POST(HttpRequest.BodyPublishers.ofString(jsonStr))
.build();
HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
return httpResponse;
}
You can find the complete program on GitHub with instructions on how to build and run it.
Advantages of using HTTP Client:
- Improved Support for HTTP, HTTP/2
- Native HTTP Feel, HTTP is a first class citizen
- Requests can be sent either synchronously or asynchronously
- Simple and straight API
Below is a comparison table of various Java HTTP clients.
Java version compatibility (current version of client) | Original release date | Latest release (as of September 2020) | Sync/Async | Async API style(s) | HTTP/2 | Forms | Multipart / file upload | Cookies | Authentication | Transparent content compression | Caching | Websockets | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
HttpURLConnection |
1.1+ (HTTP) 1.4+ (HTTPS) |
1997 (with JDK 1.1) 2002 (with JDK 1.4) |
September 2020 (with Java SE 15) | Sync only | N/A | No | No | No | No | None | No | No | No |
Java HttpClient |
11+ | September 2018 (with Java SE 11) | September 2020 (with Java SE 15) | Both | Futures | Yes | No | No | Yes | Basic (not pre-emptive) Pluggable | No | No | Yes |
Apache HTTPClient |
7+ | 2001 | September 2020 | Both | Futures | Currently only in the 5.1 beta | Yes | Yes | Yes | Basic Digest NTLM SPNEGO Kerberos Pluggable |
GZip Deflate | Yes | No |
OkHttp |
8+ | 2013 | September 2020 | Both | Callbacks | Yes | Yes | Yes | Yes | Pluggable | GZip Deflate Brotli | Yes | Yes |
AsyncHttpClient | 8+ | 2010 | April 2020 | Async only | Futures Callbacks Reactive streams | No | Yes | Yes | Yes | None | No | Yes | Yes |
Jetty HttpClient |
8+ | 2009 | July 2020 | Both | Callbacks | Yes | Yes | Yes | Yes | Basic Digest SPNEGO Pluggable |
GZip | No | Yes |
Conclusion
We hope this helped you understand how to quickly create and consume REST services in a Java app. As you can see, it's fairly straightforward to go with the standard HTTP client that comes with JDK, but if that doesn't fit your need or you're looking for extra bells and whistles, you can choose any other library from the table above. If you have any questions or comments, please post them here.
Opinions expressed by DZone contributors are their own.
Comments