如何使用 cURL 发送带有请求参数的 POST 请求?

How to send POST-request with request arguments using cURL?

我正在尝试使用 cURL 向我的本地应用程序发送 POST-请求:

host="http://localhost:8080"
$(curl -s -X POST -H "Content-Type: application/json" -d '{"name":"Test", "description":"Test"}' $host/games/new?user_id=c13fb734-c72a-48a0-9fd7-5fbc79c6285a)

我的控制器:

@RequestMapping("games")
@RestController
public class GameController {

    private static final String ROOT_URL = ServerConfig.GAMES_HOST + "/games";

    @PostMapping(value = "new")
    public ResponseEntity<String> add(@RequestParam("user_id") UUID userId,
                      @RequestBody String newGame) {
        String url = ROOT_URL + "/new?userId=" + String.valueOf(userId);
        RestTemplate template = new RestTemplate();
        return template.postForEntity(url, newGame, String.class);
    }
}

但在 Spring 中出现错误:

{"errors":["user_id should be of type java.util.UUID"],"status":"BAD_REQUEST","message":"Failed to convert value of type 'java.lang.String' to required type 'java.util.UUID'; nested exception is java.lang.IllegalArgumentException: Invalid UUID string: new"}

即cURL 发送 new 作为 user_id 的值。 错误在哪里?

分析

长话短说,从概念上讲,@RequestParam@RequestBody 是互斥的:查询参数 (@RequestParam) 作为请求正文发送。

请在此处查看更多详细信息:

  • .
  • Spring MVC - Why not able to use @RequestBody and @RequestParam together.
  • .
  • .

解决方案

目前有两种选择:

  1. 仅坚持请求参数 (@RequestParam):将每个参数(即每个 JSON 属性)作为查询参数传递。
  2. 仅坚持请求正文 (@RequestBody),例如:

    1. 将所有内容作为 JSON 请求正文传递。
    2. 将所有内容作为 JSON 请求正文传递,user_id 参数除外。参数可以设为 @PathVariable 并且 @RequestMapping 应该使用适当的占位符来引用它。