Monday, September 30, 2024

How to send a POST request in Java using HttpClient? Example Tutorial

Hello guys, if you are wondering how to send an HTTP POST request from Java program then don't worry, Java has classes like HttpClient and HttpURLConnection which you can use to send any HTTP request including POST. In the previous article, I showed you how to create a REST Client in Java and in this article, I am going to show you how to send a POST request from Java Program. I have used new HttpClient API from Java 11 as this is the recommend API for sending HTTP request and parsing HTTP response in Java but if you are not using Java 11 then you can either use HttpURLConnection or any third party library like Spring Framework or Apache HttpClient to send POST request from Java program.


Anyway, enough talking,  let's jump into the code now


How to send a POST request in Java using HttpClient API

Here's an example of how to send a POST request in Java using HttpClient class of Java 11. This code creates an HTTP POST request using the HttpRequest.Builder class, an example of builder pattern. 

The request body is created using the HttpRequest.BodyPublishers.ofString() method, which creates a request body from a string. The request header, "Content-Type" is then set using the HttpRequest.Builder.header() method to indicate that request is in JSON format. 

The request is then sent using the HttpClient.send() method and the response body is obtained using the HttpResponse.BodyHandlers.ofString() method, which returns the response body as a string. 

This class provides many nice methods like ofStream() and ofFile() to receive response as Stream or save into file.

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class RESTClient {

  private final HttpClient client;

  public RESTClient() {
    client = HttpClient.newBuilder()
      .build();
  }

  public void sendPostRequest() {
    try {
      String requestBody = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";
      HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(requestBody))
        .build();
      HttpResponse<String> response 
 = client.send(request, HttpResponse.BodyHandlers.ofString());
      System.out.println("Status: " + response.statusCode());
      System.out.println("Content: " + response.body());
    } catch (Exception e) {
      System.out.println("Error sending POST request: " + e.getMessage());
    }
  }

  public static void main(String[] args) {
    RESTClient restClient = new RESTClient();
    restClient.sendPostRequest();
  }
}


When you run the code, it will send an HTTP POST request to the specified endpoint https://jsonplaceholder.typicode.com/posts, with a request body that contains a JSON payload. If the request is successful, the response status code, mostly 200 and 201 and response body will be printed to the console as shown below:

Status: 201
Content: {
  "id": 101
}


Note that the exact output will depend on the specific endpoint and the payload that you are sending. In this example, the response status code 201 indicates that the request was successful and that the resource was created. The response body contains the data returned by the server, which in this case is a JSON object with a single key "id" and its value.

So, you can see how easy it is now to send a POST request using HttpClient class in Java. 

How to send a POST request in Java using HttpClient? Example Tutorial



Things to remember while sending POST Request

Since POST requests are not idempotent and resubmit of POST request can cause issues, you should be careful while sending POST request to server. Here are some things to remember when sending a POST request in Java using HttpClient:


1. Endpoint

You should first make sure you have the correct endpoint URL for your POST request. The endpoint should be a valid URL that accepts POST requests.


2. Request Body

Make sure the request body is correctly formatted and contains the correct data for the endpoint.


3. Request Headers

Make sure to set any required headers for the request. For example, the Content-Type header should be set to application/json if you are sending a JSON payload in the request body.


4. HTTP Method

Make sure the correct HTTP method is used for the request. In this case, the method should be POST.


5. Error Handling

Make sure to handle errors and exceptions that may occur while making the request. For example, if the endpoint is down or there is a network issue, the request may fail and you should handle this case gracefully in your code.


6. Response Handling

Make sure to handle the response properly and extract the data you need from the response. For example, you may need to parse the response body as JSON or XML.


7. Timeout

You must set a reasonable timeout for the request to avoid waiting indefinitely for a response. You can also set a timeout using the HttpClient.Builder.connectTimeout() method which is timeout for connection establishment. There are also request level timeout, you should also set that. 


These are a couple of things every Java developer should remember while sending POST request to any server. By following this guideline you u can ensure that your POST request is properly formatted and handled, and that you can handle any errors or issues that may occur during the request.



How do we send large data using POST like data over 10 MB?

Sending POST request itself is not easy but it becomes tricky when you have to send a large data like a big JSON file. Anyway, here are few things you should consider while sending large data using a POST request:


1. Chunking
The HttpClient class can handle chunked data transfers, where the data is divided into smaller chunks and sent in multiple requests. You can enable chunking by setting the Transfer-Encoding header to chunked.


2. Compression
Compressing the data before sending it can reduce the size of the payload and improve the performance of the request. You can use a compression algorithm such as GZIP to compress the data before sending it.

3. Streaming
You can stream the data to the server instead of loading it into memory all at once. This can be useful for large data transfers, as it allows you to send the data in chunks without having to load the entire payload into memory.



Here's an example of how to send large data using the HttpClient class

In this example, the data is compressed using GZIP and sent in chunks using the HttpRequest.BodyPublishers.ofInputStream() method. The Content-Encoding header is set to gzip to indicate that the data is compressed. The response is handled in the same way as a normal POST request.
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.zip.GZIPOutputStream;

public class LargeDataPOST {

  private final HttpClient client;

  public LargeDataPOST() {
    client = HttpClient.newBuilder()
      .build();
  }

  public void sendLargeData() {
    try {
      InputStream dataStream = getDataStream();
      HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://api.example.com/large-data"))
        .header("Content-Encoding", "gzip")
        .POST(HttpRequest.BodyPublishers.ofInputStream(() -> {
          try (GZIPOutputStream gzip = new GZIPOutputStream(dataStream)) {
            return gzip;
          }
        }))
        .build();
      HttpResponse<String> response 
  = client.send(request, HttpResponse.BodyHandlers.ofString());
      System.out.println("Status: " + response.statusCode());
      System.out.println("Content: " + response.body());
    } catch (Exception e) {
      System.out.println("Error sending POST request: " 
     + e.getMessage());
    }
  }

  private InputStream getDataStream() {
    // return the InputStream containing the large data
  }

  public static void main(String[] args) {
    LargeDataPOST largeDataPOST = new LargeDataPOST();
    largeDataPOST.sendLargeData();
  }
}


That's all about how to send a POST Request in Java. I have shown you how you can use HttpClient class to send POST request form Java program without using any third party library. I have also taught you best practices to consider while sending POST request and we have seen some of them in order to send large amount of data via POST request like compression, chunking and streaming. 

If you have any questions, feel free to ask in comments.

All the best with your learning and switch to Java 11 if you are still not using it. 


No comments:

Post a Comment