我正在测试我的应用程序,发现了一些奇怪的东西。
我的代码:
@RequestMapping(value = "/test/{subscriberId}", method = RequestMethod.PATCH, consumes = "application/json", produces = "application/json")
public void test(@PathVariable final String subscriberId,@RequestBody Boolean actDeact ) {
..
}
当我通过 postman 提出请求时,我收到了 400 个错误请求:
我不明白为什么会发生这种情况。
我认为我的第一次尝试是有效的。如果我等待一个字符串,也会发生同样的情况 (我没有收到错误代码 400,但将字符串内的所有正文传递给我)
谁能解释一下吗?
最佳答案
尝试这样:
public class MyPojo
{
private Boolean actDeact;
private String subscriberId;
// you can add it if you want more ..
public Boolean getActDeact() {
return actDeact;
}
public void setActDeact(Boolean actDeact) {
this.actDeact = actDeact;
}
public String getSubscriberId() {
return subscriberId;
}
public void setSubscriberId(String subscriberId) {
this.subscriberId = subscriberId;
}
}
@RequestBody MyPojo myPojo//像这样使用它。
Spring 会将传入的 JSON 从帖子正文转换为 MyPojo 对象(因为您添加了 @RequestBody 注释),并将返回的对象序列化为 JSON(因为您添加了 @ResponseBody 注释)。
可以引用一下 https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc 了解更多。
注意:
@RequestParam annotated parameters get linked to specific Servlet request parameters. Parameter values are converted to the declared method argument type. This annotation indicates that a method parameter should be bound to a web request parameter.
如果您想发送,可以使用@RequestParam: 字符串、 boolean 值作为不带包装器的参数。
同样的方法
@RequestBody annotated parameters get linked to the HTTP request body. Parameter values are converted to the declared method argument type using HttpMessageConverters. This annotation indicates a method parameter should be bound to the body of the web request.
那么你在哪里发送 true 这不是一身有法。 它无法工作或转换为 json 所以它会返回一些 400 状态代码
400 Bad Request 响应代码的扩展。 如果您还需要了解更多信息,可以阅读该文档 Spring 。 我希望这可以帮助你.... 谢谢..
关于java - Spring RequestBody 与 Postman 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50697106/