Home > Software design >  How to use RestTemplate for a POST request for a complex body in Java?
How to use RestTemplate for a POST request for a complex body in Java?

Time:02-23

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", "[email protected]");
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!

CodePudding user response:

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);

CodePudding user response:

My suggestion is to use some other Http client and not RestTemplate. So if you have to use RestTemplate this answer is not relevant. I wrote my own Http client, and while it might be limited in what it can do its major advantage is simplicity. Your code may look like:

HttpClient client = new HttpClient();
String response = client.sendHttpRequest("www.myurl.com", HttpClient.HttpMethod.POST, "{\"yourJson\":\"here\"");

Here is Javadoc for HttpClient class. The library can be obtained as Maven artifacts or on Github (including source code and javadoc)

  • Related