我有一个带有几个方法的控制器类,其中一个方法是应该接受 POST 请求并使用来自该 POST 请求正文的 JSON 创建一个新帐户的方法。
当我尝试使用 curl 发出 POST 请求时,我收到一个错误消息
{"timestamp":1493988808871,"status":400,"error":"Bad Request","exception":"org.springframework.http.converter.HttpMessageNotReadableException","message":"Required request body is missing: org.springframework.http.ResponseEntity<?> com.example.AccountRestController.add(java.lang.String,java.lang.String)","path":"/users/add"}
我正在使用的 curl 命令
curl -X POST --data '{"userName":"bepis", "password":"xyz"}' -H "Content-Type:application/json" http://localhost:8080/users/add
帐户休息控制器
@RequestMapping(method = RequestMethod.POST, value = "/add", produces = { MediaType.APPLICATION_JSON_VALUE})
ResponseEntity<?> add(@RequestBody String username, @RequestBody String password) {
Account result = accountRepository.save(new Account (username, password));
return new ResponseEntity<>(result, HttpStatus.CREATED);
}
您不能使用多个@RequestBody
. 您需要将所有内容包装到一个用于匹配您的请求正文的类中。
这里也有同样的回答。
对于被拒绝的功能请求,还有一个JIRA 问题。
注意:如果你想写得更少,你可以使用@PostMapping
代替@RequestMapping(method = RequestMethod.POST)
.
注意: @RequestParam
and@PathVariable
用于从 URI 中提取数据,而不是从正文中提取数据。
注意:这同样适用于[FromBody]
来自的等效属性ASP.NET WebAPI
。
完整示例:
波纹管我创建了一个类似于您的案例的工作示例:
请求 DTO
public class AccountCreateRequest {
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
响应 DTO
public class AccountCreateResponse {
private String userName;
private String password;
public AccountCreateResponse() {
}
public AccountCreateResponse(String userName, String password) {
this.userName = userName;
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
控制器
@RestController
@RequestMapping("/v1/account")
public class AccountController {
@PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseStatus(HttpStatus.CREATED) AccountCreateResponse add(@RequestBody() AccountCreateRequest account) {
AccountCreateResponse response = new AccountCreateResponse(account.getUserName(), account.getPassword());
return response;
}
}
卷曲请求
curl -X POST --data '{"userName":"bepis", "password":"xyz"}' -H "Content-Type:application/json" http://localhost:8080/v1/account
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句