gpt4 book ai didi

java - 如果 http 请求的内容类型是 urlencoded,如何让 Spring Boot Controller 读取对对象的 http 请求正文?

转载 作者:行者123 更新时间:2023-12-02 06:00:18 25 4
gpt4 key购买 nike

我是 spring 和 spring boot 的新手,并且已经设置了一个简单的 Controller ,如果存在将内容类型设置为 application/json 的 header 集,则该 Controller 可以读取对对象的 http 请求。

但是,当我不在 header 中设置内容类型时,这不起作用,并且出现错误:“Content type 'application/x-www-form-urlencoded;charset=UTF-8'不支持”。我知道我从来没有告诉 Controller 我实际上希望它以 JSON 形式而不是 urlencoded 形式读取正文,并且我正在寻找一种方法来执行此操作。

我已经尝试过 @RequestBody@RequestParam@ResponseBody 注释,但到目前为止还没有成功。

我还考虑过通过设置默认和其他媒体类型来覆盖 WebMvcConfigurer.configureContentNegotiation 方法,但不太清楚我在这里做什么。

这是我当前形式的简单 Controller

public class GreetingController {
@RequestMapping(value = "/greeting",
method = RequestMethod.POST)
public Greeting postGreeting(@RequestBody Greeting body) {
return new Greeting(body.getId(),"hello " + body.getContent());
}
}

这是我的问候语类的构造函数供引用:

public Greeting(long id, String content) {
this.id = id;
this.content = content;
}

我的请求正文是'{"id":10, "content": "world"}'

理想情况下,我希望找到一种方法能够将没有设置内容类型 header (因此大概默认为 form-urlencoded)的 HTTP 请求处理为 JSON,这样在设置帖子时就不需要考虑太多请求并且 Controller 不那么脆弱。

最佳答案

试试这个:

    @RestController
public class GreetingController {
@RequestMapping(value = "/greeting",
method = RequestMethod.POST)
public HttpEntity<String> postGreeting(@RequestBody Greeting body) {
//SETGREETING()
return new HttpEntity<String>("data has been saved");
}
}

并且不要忘记接受 application/json header 。

关于java - 如果 http 请求的内容类型是 urlencoded,如何让 Spring Boot Controller 读取对对象的 http 请求正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55982465/

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