Search code examples
javaspringspring-bootresttemplate

How to use RestTemplate for a POST request for a complex body in Java?


I'm working with RestTemplate in a Spring Boot project and I try to call a POST. And I'm using this code:

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("email", "abc@email.com");
map.add("id", "1234567");

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

ResponseEntity<Employ> response = restTemplate.postForEntity(
        "url", request , Employ.class );

Now I want to use RestTemplate to consume a POST request but for a complex object. So the body should look like this:

{
"SomeThing":{
  "Expr":"cdjhcdjh" 
},
"SomeInfo":{
 "Progr":"EVZpoiuyt",
 "Other": "{code: \"abcd\", password:\"12345\"}"
 }
}

How can I create the Map for this body? Any feedback will be apreciated. Thank you!


Solution

  • You should create Java objects (POJO) representing the data you would like to send via RestTemplate.

    For example:

    public class ObjectToPost {
      private SomeThing someThing;
      private SomeInfo someInfo;
    
     // getters & setters
    }
    
    public class SomeThing {
     private String expr;
         
     // getters & setters
    }
    
    public class SomeInfo {
      private String progr;
      private String other;
         
      // getters & setters
    }
    

    Then you could use this object in your RestTemplate.

    ObjectToPost obj = new ObjectToPost();
    obj.setSomeThing(...)
    obj.setSomeInfo(...)
    restTemplate.postForEntity("url", obj , Employ.class);
    

    You could also use a Map but it will make it quite complex. If you really would like to achieve it with a Map you should create a <String,Object> map like:

      MultiValueMap<String, Object> map= new LinkedMultiValueMap<String, Object>();
      MultiValueMap<String, MultiValueMap<String, Object>> somethingMap = new LinkedMultiValueMap<String, Object>();
      something.put("SomeThing", Map.of("Expr","cdjhcdjh");
      map.put(somethingMap);