gpt4 book ai didi

java - Spring RequestBody 与 Postman 测试

转载 作者:行者123 更新时间:2023-11-30 02:08:47 25 4
gpt4 key购买 nike

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

我的代码:

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com