![](/img/trans.png)
[英]HTTP Post request with content type application/x-www-form-urlencoded not working in Spring boot service
[英]How can I get my spring boot controller to read the body of my http request to an object if the http request has content type urlencoded?
我是spring和spring boot的新手,并设置了一个简单的控制器,如果有一个标题集将content-type设置为application/json
,它可以读取对象的http请求。
但是,当我没有在标题中设置内容类型时,这不起作用,我得到错误: "Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported"
。 我明白,在任何时候我都没有告诉控制器我实际上是想让它以JSON而不是urlencoded来读取正文,而我正在寻找一种方法。
我已经尝试了@RequestBody
@ResponseBody
, @RequestParam
@ResponseBody
和@ResponseBody
注释,但到目前为止还没有运气。
我还通过设置默认和其他媒体类型来查看覆盖WebMvcConfigurer.configureContentNegotiation
方法,但我不清楚我在这里做什么。
这是我当前形式的简单控制器
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"}'
理想情况下,我想找到一种方法能够处理一个没有内容类型标头集的http请求(因此可能默认为form-urlencoded)作为JSON,这样在设置post请求时就不用考虑了控制器不那么脆弱。
尝试这个:
@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标头。
请尝试以下代码导入org.springframework.web.bind.annotation.ModelAttribute;
public class GreetingController {
@RequestMapping(value = "/greeting",
method = RequestMethod.POST)
public Greeting postGreeting(@ModelAttribute Greeting body) {
return new Greeting(body.getId(),"hello " + body.getContent());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.