【问题标题】:How to send POST-request with request arguments using cURL?如何使用 cURL 发送带有请求参数的 POST 请求?
【发布时间】:2018-06-29 13:23:05
【问题描述】:

我正在尝试使用 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);
    }
}

但是在春天我得到一个错误:

{"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 的值发送。 哪里会出错?

【问题讨论】:

  • 如果在 JSON 中包含 user_id 会怎样?喜欢-d '{"name":"Test", "description":"Test", "user_id":"c13fb734-c72a-48a0-9fd7-5fbc79c6285a"}'

标签: java curl spring-rest


【解决方案1】:

分析

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

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

解决方案

目前有两种选择:

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

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

【讨论】:

    猜你喜欢
    • 2022-08-14
    • 2011-04-12
    • 2015-07-22
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 2019-10-27
    相关资源
    最近更新 更多