16

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;
    }
pethel
  • 5,397
  • 12
  • 55
  • 86
  • Is your controller annotated to include the `user` portion of the path in `@RequestMapping`? Because your metohd annotated points to `/`, which isn't going to respond to `/user/` without the additional controller annotation. – nicholas.hauschild Oct 04 '12 at 13:23
  • @nicholas.hauschild Yes. I am entering the controller method. The problem is that the Profile is null in the actual method. – pethel Oct 04 '12 at 13:31

3 Answers3

17

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);
pethel
  • 5,397
  • 12
  • 55
  • 86
4

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);
Mihkel Selgal
  • 508
  • 6
  • 10
1

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);
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Antonio682
  • 363
  • 1
  • 4
  • 18