Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
like image 804
pethel Avatar asked Oct 04 '12 13:10

pethel


People also ask

How do you POST data with RestTemplate?

Posting JSON With postForObject. RestTemplate's postForObject method creates a new resource by posting an object to the given URI template. It returns the result as automatically converted to the type specified in the responseType parameter.

How is postForEntity used in RestTemplate?

Using postForEntity() Find the postForEntity method declaration from Spring doc. url: The URL to post the request. request: The object to be posted. responseType: The type of response body.

What is difference between getForObject and getForEntity?

For example, the method getForObject() will perform a GET and return an object. getForEntity() : executes a GET request and returns an object of ResponseEntity class that contains both the status code and the resource as an object. getForObject() : similar to getForEntity() , but returns the resource directly.


3 Answers

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);
like image 45
Mihkel Selgal Avatar answered Sep 28 '22 05:09

Mihkel Selgal


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);
like image 126
pethel Avatar answered Sep 28 '22 05:09

pethel


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);
like image 30
Antonio682 Avatar answered Sep 28 '22 06:09

Antonio682