“HttpMessageNotReadableException Required request body is missing” when trying to make a post request

后端 未结 2 1704
心在旅途
心在旅途 2021-01-14 05:10

I have a controller class with a few methods one of which is a method that is supposed to take POST requests and create a new Account with the JSON from the body of that POS

2条回答
  •  轮回少年
    2021-01-14 05:35

    You cannot use multiple @RequestBody. You need to wrap everything into a class that will be used to match your request body.

    The same is answered also here.

    There is also a JIRA issue for a feature request which was rejected.

    NOTE: if you want to write less, you can use @PostMapping instead of @RequestMapping(method = RequestMethod.POST).

    NOTE: @RequestParam and @PathVariable are used to extract data from URI, not from body.

    NOTE: the same is valid also for the equivalent [FromBody] attribute from ASP.NET WebAPI.

    Complete example:

    Bellow I created a working example similar to your case:

    Request 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;
        }
    }
    

    Response 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;
        }
    }
    

    Controller

    @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 request

    curl -X POST --data '{"userName":"bepis", "password":"xyz"}' -H "Content-Type:application/json" http://localhost:8080/v1/account
    

提交回复
热议问题