尝试发出发布请求时,Spring Boot“ HttpMessageNotReadableException缺少所需的请求正文”

闪电吉米·乔·约翰逊

我有一个带有一些方法的控制器类,其中一种方法应该接收POST请求,并从该POST请求的主体中使用JSON创建一个新Account。

当我尝试使用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

AccountRestController

@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@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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章