httpclient post raw json body

How to make a HTTP POST request with raw JSON body using HttpClient in Java?

If you want to make a HTTP POST request with raw JSON body using HttpClient in Java, you can do this in several ways:

Method 1: Using StringEntity

One way is to use StringEntity class provided by HttpClient. Here is the code:


  // Create HttpClient instance
  HttpClient client = HttpClientBuilder.create().build();

  // Set URL
  HttpPost httpPost = new HttpPost("http://example.com/api/resource");

  // Set headers
  httpPost.setHeader("Content-Type", "application/json");

  // Set request body
  String jsonBody = "{\"key\": \"value\"}";
  StringEntity entity = new StringEntity(jsonBody);
  httpPost.setEntity(entity);

  // Execute HTTP POST request
  HttpResponse response = client.execute(httpPost);
  

Method 2: Using JSONObject

Another way is to use JSONObject class from JSON library. Here is the code:


  // Create HttpClient instance
  HttpClient client = HttpClientBuilder.create().build();

  // Set URL
  HttpPost httpPost = new HttpPost("http://example.com/api/resource");

  // Set headers
  httpPost.setHeader("Content-Type", "application/json");

  // Set request body
  JSONObject jsonBody = new JSONObject();
  jsonBody.put("key", "value");
  StringEntity entity = new StringEntity(jsonBody.toString());
  httpPost.setEntity(entity);

  // Execute HTTP POST request
  HttpResponse response = client.execute(httpPost);
  

Method 3: Using Gson

A third way is to use Gson library which provides a convenient way to serialize Java objects to JSON and vice versa. Here is the code:


  // Create HttpClient instance
  HttpClient client = HttpClientBuilder.create().build();

  // Set URL
  HttpPost httpPost = new HttpPost("http://example.com/api/resource");

  // Set headers
  httpPost.setHeader("Content-Type", "application/json");

  // Set request body
  Gson gson = new Gson();
  Map<String, String> jsonBody = new HashMap<>();
  jsonBody.put("key", "value");
  String json = gson.toJson(jsonBody);
  StringEntity entity = new StringEntity(json);
  httpPost.setEntity(entity);

  // Execute HTTP POST request
  HttpResponse response = client.execute(httpPost);
  

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe