Search code examples
javaapipostapache-httpclient-4.xorg.json

How to send hashmap as JsonObject to a webservice in Java


I am trying to make a POST request with a hashmap. The accepted format by the webservice is given below.

{ 
"students": [
         {
            "firstName": "Abc",
            "lastName": "XYZ",
            "courses": [
            "Math",
            "English"
            ]
          }
}

This is my code

HttpClient client2 = HttpClient.newBuilder().build();
HttpRequest request2 = HttpRequest.newBuilder()
          .uri(URI.create(POST_URI))
          .header("Content-Type", "application/json")
          .POST(new JSONObject(myMap))
          .build();

However, this doesn't work. All the examples I have seen so far only accept string as POST parameter and not map.


Solution

  • In your case it seems that you are using the java http client introduced in Java 11. This client required a BodyPublisher to send POST requests.

    The java.net.http.BodyPublishers class provide you a method named #ofString(String body) that you can use to send body.

    So you can just build your HttpRequest like that :

    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create(POST_URI))
        .header("Content-Type", "application/json")
        .POST(BodyPublishers.ofString(yourBody))
        .build();
    

    In this case you need to pass a string to the ofString method, so you can use a library like Jackson or Gson. I don't know how to do this using Gson but using Jackson it is very simple :

    ObjectMapper mapper = new ObjectMapper();
    
    String yourBody = mapper.writeValueAsString(yourMap);
    
    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create(POST_URI))
        .header("Content-Type", "application/json")
        .POST(BodyPublishers.ofString(yourBody))
        .build();
    

    That's all :)

    EDIT: After a second reading, I would like to point out that you cannot send java objects as is in an http request. You already need to transform your objects in a readable format for the server like json or XML. Java objects are part of the programs we write, the Http protocol is not able to pass these objects as is. That's why we use an intermediate format, thus the server is able to read this format and transform it back into an object