【问题标题】:Spring post json春季发布 json
【发布时间】:2021-03-01 22:50:57
【问题描述】:

我尝试构建我的第一个 api。我想注册新用户时遇到问题。问题是当我想从邮递员发送请求时。我也使用 SwaggerUI,所以当我通过文本字段在 SwaggerUI 中使用 Post Request 到我的终点/注册时,我总是得到 http 状态 201,所以它工作得很好。问题是当我想对这个控制器进行 Mock 或者当我想在邮递员请求中发送新用户时,但并非总是如此。我用例子给你看

如果我使用邮递员 -> post: localhost:8080/registration -> Raw -> JSON

{
  "email": "testtest@gmail.com",
  "id": 0,
  "password": "Test1234567  ",
  "username": "testtest"
}

然后我收到消息

{
    "status": "BAD_REQUEST",
    "timestamp": "01-03-2021 11:44:26",
    "message": "Value cannot be empty!",
    "debugMessage": null,
    "subErrors": null
}

所以它应该很好,因为我使用了 catch 异常。但是值不是空的,所以发生了什么?我不知道。 但是当我转到 x-www-form-urlencoded 并在那里输入密钥:电子邮件、用户名和密码时,用户就被创建了!

另一个,当我把同样的信息放到 Swagger 上时,我的用户也被创建了。

下面我从控制器添加我的代码并进行测试。

@Test
void shouldCreateNewUser() throws Exception {
    UserRegistrationDto user = new UserRegistrationDto( null,"seba12345", "lelelele1908@gmail.com", passwordEncoder.encode("Respeck123"));

    mockMvc.perform(post("/registration")
            .header("header1", "1")
            .contentType(MediaType.APPLICATION_JSON)
            .content(objectMapper.writeValueAsString(user)))
            .andExpect(status().isCreated());
}



@PostMapping("/registration")
public ResponseEntity<UserRegistrationDto> registerUser(UserRegistrationDto userRegistrationDto) {
    HttpHeaders headers = new HttpHeaders();
    userService.save(userRegistrationDto);

    return new ResponseEntity<>(userRegistrationDto, headers, HttpStatus.CREATED);
}

【问题讨论】:

    标签: java json spring post


    【解决方案1】:

    您需要在控制器方法中使用@RequestBody 来告诉 Spring 您想要请求正文的内容:

    @PostMapping("/registration")
    public void post(@RequestBody MyDTO dto) {
      ...
    }
    

    【讨论】:

    • 谢谢 :) 这很简单,我花了很多时间从另一边寻找问题。
    猜你喜欢
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多