gpt4 book ai didi

java - POST 调用接受 x-www-form-urlencoded 但拒绝 JSON

转载 作者:行者123 更新时间:2023-11-30 01:46:09 25 4
gpt4 key购买 nike

我正在尝试进行 POST 调用。
我的正文只有一个参数,因此我想简单地使用 @RequestParam 来读取它。
代码:

    @RequestMapping(value = "/call", method = RequestMethod.POST)
@ResponseBody
public void doStuff(@RequestParam List<Integer> nums,
HttpServletResponse response) {

使用x-www-form-urlencoded进行的调用工作正常-

curl -X POST https://localhost:9002/call

-H 'Authorization: bearer d1436121-25f7-4162-b0d4-7699d4acf147'
-H 'Content-Type: application/x-www-form-urlencoded'
-H 'Host: localhost:9002'
-d nums=0%2C1%2C3

<小时/>

但是使用 JSON 进行同样的调用会失败。
代码:

        @RequestMapping(value = "/call", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public void doStuff(@RequestParam List<Integer> nums,
HttpServletResponse response) {

调用 application/json 失败 -

curl -X POST https://localhost:9002/call
-H 'Authorization: bearer d1436121-25f7-4162-b0d4-699d4acf147'
-H 'Content-Type: application/json'
-H 'Host: localhost:9002'
-d '{ "nums":[0,1,3] }'

错误:

{ "errors": [ { "message": "Leider ist ein Fehler aufgetreten.", "type": "MissingServletRequestParameterError" } ] }

为什么它接受x-www-form-urlencoded但拒绝JSON

最佳答案

您只能将 @RequestParam 与 URL 查询参数、表单数据或多部分负载一起使用。如果您想使用 JSON 负载,则应使用 @RequestBody 注释并将该 JSON 映射到 Java 对象。

来自https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestParam.html

In Spring MVC, "request parameters" map to query parameters, form data, and parts in multipart requests. This is because the Servlet API combines query parameters and form data into a single map called "parameters", and that includes automatic parsing of the request body.

关于java - POST 调用接受 x-www-form-urlencoded 但拒绝 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57870146/

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