DZone
Java Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Java Zone > How to Consume REST Web Service (GET/POST) in Java 11 or Above

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.

Suyash Joshi user avatar by
Suyash Joshi
·
Jan. 11, 22 · Java Zone · Tutorial
Like (5)
Save
Tweet
3.56K Views

Join the DZone community and get the full member experience.

Join For Free

RESTful 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. 

Java
 
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:

Java
 
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.

Java
 
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. 

Java
 
client.sendAsync(getRequest, BodyHandlers.ofString())
      .thenApply(HttpResponse::body)
      .thenAccept(System.out::println)
      .join();

Example with RingCentral Platform:

Java
 
 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
Old Java logo
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
New Java logo
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 HTTP Components logo
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
Square logo
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 logo
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.

Java (programming language) REST Web Protocols Web Service

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Take Control of Your Application Security
  • How To Integrate Third-Party Login Systems in Your Web App Using OAuth 2.0
  • The Evolution of Configuration Management: IaC vs. GitOps
  • Stupid Things Orgs Do That Kill Productivity w/ Netflix, FloSports & Refactoring.club

Comments

Java Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo