pethel
pethel

Reputation: 5537

RestTemplate post for entity

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

Upvotes: 17

Views: 68736

Answers (3)

Antonio682
Antonio682

Reputation: 373

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

Upvotes: 1

Mihkel Selgal
Mihkel Selgal

Reputation: 508

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

Upvotes: 4

pethel
pethel

Reputation: 5537

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

Upvotes: 18

Related Questions