RestTemplate post for entity
63,169
Solution 1
You have to build the profile object this way
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add("email", email);
Object response = restTemplate.postForObject("http://localhost:8080/user/", parts, String.class);
Solution 2
MultiValueMap
was good starting point for me but in my case it still posted empty object to @RestController
my solution for entity creation and posting ended up looking like so:
HashedMap requestBody = new HashedMap();
requestBody.put("eventType", "testDeliveryEvent");
requestBody.put("sendType", "SINGLE");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// Jackson ObjectMapper to convert requestBody to JSON
String json = new ObjectMapper().writeValueAsString(request);
HttpEntity<String> entity = new HttpEntity<>(json, headers);
restTemplate.postForEntity("/generate", entity, String.class);
Solution 3
My current approach:
final Person person = Person.builder().name("antonio").build();
final ResponseEntity response = restTemplate.postForEntity(
new URL("http://localhost:" + port + "/person/aggregate").toString(),
person, Person.class);
Author by
pethel
Updated on July 09, 2022Comments
-
pethel almost 2 years
My post method gets called but my Profile is empty. What is wrong with this approach? Must I use @Requestbody to use the RestTemplate?
Profile profile = new Profile(); profile.setEmail(email); String response = restTemplate.postForObject("http://localhost:8080/user/", profile, String.class); @RequestMapping(value = "/", method = RequestMethod.POST) public @ResponseBody Object postUser(@Valid Profile profile, BindingResult bindingResult, HttpServletResponse response) { //Profile is null return profile; }