java - Spring RequestBody 与 Postman 测试

标签 java rest spring-mvc postman spring-annotations

我正在测试我的应用程序,发现了一些奇怪的东西。

我的代码:

  @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 个错误请求: enter image description here

但是当我在体内仅传递 true 时,一切正常: enter image description here

我不明白为什么会发生这种情况。

我认为我的第一次尝试是有效的。如果我等待一个字符串,也会发生同样的情况 (我没有收到错误代码 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/

相关文章:

java - Spring MVC - 严重 : Exception starting filter Spring OpenEntityManagerInViewFilter

Java 套接字卡住

java - 从文本文件中获取数字列表,转换为单个字符串,然后用空格或逗号将该列表拆分为两个数组列表

java - 当 java 程序出现异常时(从 shellscropt 运行 java 程序)如何只打印退出代码?

rest - 如何从 ddd 中的另一个限界上下文检索数据?

REST API 测试 : How to get response using Google Chrome developer tools?

java - 在 Swing 中更改 JTable 列中的下拉内容

rest - 谷歌主页操作休息 api 调用

spring - AngularJS $Http CORS 与 Spring Rest & Security 中的后端

java - Spring自定义身份验证过滤器和提供者不调用 Controller 方法