Java HttpClient POST JSON Example - Send JSON Data

In this source code example, we will write a Java program that uses HTTP Client API to submit form data in a JSON format(application/json).

We will use Java 11 HttpClient API to send a POST request with JSON data in a request body.

Java HttpClient POST JSON Example - Send JSON Data

import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {

    public static void main(String[] args) throws IOException, InterruptedException {

        // json formatted data
        String json = new StringBuilder()
                .append("{")
                .append("\"firstName\":\"tom\",")
                .append("\"lastName\":\"cruise\",")
                .append("\"age\":\"50\"")
                .append("}").toString();

        HttpClient client = HttpClient.newHttpClient();

        HttpRequest request = HttpRequest.newBuilder()
                .header("Content-Type", "application/json")
                .uri(URI.create("https://httpbin.org/post"))
                .POST(HttpRequest.BodyPublishers.ofString(json))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("Status code: " + response.statusCode());
        System.out.println("\n Body: " + response.body());
    }
}

Output:

Status code: 200

 Body: {
  "args": {}, 
  "data": "{\"firstName\":\"tom\",\"lastName\":\"cruise\",\"age\":\"50\"}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Content-Length": "50", 
    "Content-Type": "application/json", 
    "Host": "httpbin.org", 
    "User-Agent": "Java-http-client/17.0.2", 
    "X-Amzn-Trace-Id": "Root=1-63070480-32c7ceee01c7433d7dc18550"
  }, 
  "json": {
    "age": "50", 
    "firstName": "tom", 
    "lastName": "cruise"
  }, 
  "origin": "103.59.74.90", 
  "url": "https://httpbin.org/post"
}


Comments