【问题标题】:RestTemplate post for entity实体的 RestTemplate 帖子
【发布时间】:2012-09-25 12:47:18
【问题描述】:

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

【问题讨论】:

  • 您的控制器是否被注释为在@RequestMapping 中包含路径的user 部分?因为您的方法注释指向/,如果没有额外的控制器注释,它不会响应/user/
  • @nicholas.hauschild 是的。我正在输入控制器方法。问题是Profile在实际方法中为null。

标签: spring spring-mvc spring-3


【解决方案1】:

我目前的做法:

final Person person = Person.builder().name("antonio").build();

final ResponseEntity response = restTemplate.postForEntity(
         new URL("http://localhost:" + port + "/person/aggregate").toString(),
         person, Person.class);

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      您必须以这种方式构建配置文件对象

      MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
      parts.add("email", email);
      
      Object response = restTemplate.postForObject("http://localhost:8080/user/", parts, String.class);
      

      【讨论】:

        猜你喜欢
        • 2023-03-10
        • 1970-01-01
        • 1970-01-01
        • 2018-11-05
        • 2018-12-01
        • 1970-01-01
        • 2016-01-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多