spring 实体的 RestTemplate 帖子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12728006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 05:24:54  来源:igfitidea点击:

RestTemplate post for entity

springspring-mvcspring-3

提问by pethel

My post method gets called but my Profile is empty. What is wrong with this approach? Must I use @Requestbody to use the RestTemplate?

我的 post 方法被调用,但我的个人资料为空。这种方法有什么问题?我必须使用 @Requestbody 来使用 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;
    }

采纳答案by pethel

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

回答by Mihkel Selgal

MultiValueMapwas good starting point for me but in my case it still posted empty object to @RestControllermy solution for entity creation and posting ended up looking like so:

MultiValueMap对我来说是一个很好的起点,但在我的情况下,它仍然将空对象发布到@RestController我的实体创建和发布解决方案中,最终看起来像这样:

HashedMap requestBody = new HashedMap();
requestBody.put("eventType", "testDeliveryEvent");
requestBody.put("sendType", "SINGLE");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

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

回答by Antonio682

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