Introduction
Every web application communicates with the internet using requests and responses. It sends requests to the servers and processes the received responses accordingly. The response can be of different formats, but the one format that predominately has become the standard is the JSON format. And the credit goes to its brevity, small payload size, and the ease of operation.
We see, sending POST
requests to the APIs is often required. Depending on diffent programming languages, the underlying libraries and the syntax changes.
In this blog post, we will walk through how to send a POST request to a server using authenticated user credentials in Java jdk 11 using the HttpClient
library. We will also look at how to receive a JSON response from the API.
NOTE : This blog post only outlines how to create a connection and use it in any Java application. Writing and explaining the complete java code is outside the scope of this blog post. For that, please reefer to this book or perhaps check out this video.
Step 1: Setup
Before we get started, let's make sure we have everything we need. We will be using the HttpClient
library, which is included in Java jdk 11, so we will need at least java JDK 11 or higher installed on our machine. Apart from that, we would require an API endpoint that requires authentication, and valid user credentials to access that endpoint.
We will also need to include the Gson
library, which is a popular library for working with JSON
in Java. You can add this library to your project using Maven or Gradle.
So, our requirements are
- Java jdk 11 (minimum)
- API endpoint with user credentials
- Optional: Maven (or Gradle)
Step 2: Create the HttpClient
Lets do some coding. The first thing we need is that we need to create an instance of the HttpClient
. We can do this using the HttpClientBuilder
class:
// Code Snipit: 1
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.build();
This creates a new instance of the HttpClient with the HTTP/2 protocol version. Here we've specified the HTTP_2
as the version we would be making the request with.
We can also use the default HttpClient, as shown below
// Code Snipit: 2
HttpClient client = HttpClient.newHttpClient();
Both the code snipits above generate the HttpClient object. However, the code snipit 2 creates an HttpClient object which include: the GET
request method instead of POST
, a preference of HTTP/2
, a redirection policy of NEVER
, the default proxy selector, and the default SSL context.
Step 3: Create the Request
Now that we have the HttpClient
, we can create the POST request to send to the API. We will need to specify the URI of the API endpoint, as well as any headers or data that needs to be sent in the request body. We will also need to add the authentication credentials to the request headers.
We first append the username with password, using colon (:) as the connector before encoding the complete string in the base64 format.
For quick results, we can simply run this in the terminal
echo username:password | base64
Now that we've the token, lets create a request object.
// Code Snipit: 3
String uri = "https://example.com/api/endpoint";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(uri))
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{\"key\":\"value\"}"))
.build();
Normally we do not hardcode any values (such as URLs or user-credentials in the form of Bearer Token) in the program itself, in Production applications. It is stored in the configuration file (if a Maven project) or perhaps use environment variables to store the URL. In the program the value of URL can be fetched from the environment variables as shown below.
// Code Snipit: 4
String uri = env.getProperty("API_URL");
String username = env.getProperty("USERNAME");
String password = env.getProperty("PASSWORD");
String valueToEncode = username + ":" + password;
String token = "Basic " + Base64.getEncoder().encodeToString(valueToEncode.getBytes());
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(uri))
.header("Authorization", token)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{\"key\":\"value\"}"))
.build();
Here, we are just creating a POST request to the "https://example.com/api/endpoint" endpoint, adding an Authorization
header with the authentication token, a Content-Type
header with the data format, and a JSON payload with a key-value pair.
Step 4: Send the Request and Receive the Response
Finally, we can send the request using the HttpClient and receive the response from the API. We can then use the Gson
library to parse the JSON response into a Java object.
// Code Snipit: 5
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
String responseBody = response.body();
Gson gson = new Gson();
MyResponseObject responseObject = gson.fromJson(responseBody, MyResponseObject.class);
In the above snipit, we are sending the POST request using the HttpClient
and using the ofString()
method to receive the response body as a string. We then create a Gson
instance and parse the response body into a MyResponseObject
class using the fromJson()
method.
Conclusion
So, we saw how easy and simple it is to create the POST request to an API using authenticated user credentials and receive a JSON response in Java jdk 11 using the HttpClient
library. By following these steps, you can easily integrate with APIs in your Java applications.