You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Curl中传递Map<String, Object>调用Spring POST接口?

问题:如何通过Curl调用接收Map<String, Object>参数的Spring REST接口?

当前定义的Spring接口如下:

@PostMapping("/abc/aa/{type}")
private final ResponseEntity<Void> invoke(@PathVariable String type,
        @RequestParam(name = "params", required = false) Map<String, Object> params)
{
}

尝试了两种Curl调用方式,均未成功:

方式1:将params作为单个参数传递

Curl命令:

curl -G -X POST --url http://localhost:8585/abc/aa/default_aa.TEST_varchar100_94946640?params='apiTriggered=true;fromPk=7898989898'

触发类型转换错误:

{"success":false,"header":null,"data":null,"messageKey":"error.500","message":"error.500","errors":[],"exceptions":[{"messageData":{},"resource":"Throwable","messageKey":"Throwable","message":"Internal exception was caught and handled by CustomErrorController (see logs for the trace); UID: ad4e6165-7eed-4682-b587-bca6a6b2532e; message: org.springframework.web.method.annotation.MethodArgumentConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Map'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.util.Map': no matching editors or conversion strategy found","stackTrace":

方式2:直接传递多个参数

Curl命令:

curl -G -X POST --url http://localhost:8585/abc/aa/default_aa.TEST_varchar100_94946640?apiTriggered=true&fromPk=7898989898

此时接口中的params参数始终为null。


正确的接口定义与Curl调用示例

方案1:直接映射多个请求参数到Map

Spring默认支持将URL中的多个请求参数自动封装到Map<String, Object>,只需调整@RequestParam注解的写法,去掉name属性即可:

@PostMapping("/abc/aa/{type}")
private final ResponseEntity<Void> invoke(@PathVariable String type,
        @RequestParam(required = false) Map<String, Object> params)
{
}

对应的Curl调用(无需-G参数,直接通过POST传递URL查询参数):

curl -X POST "http://localhost:8585/abc/aa/default_aa.TEST_varchar100_94946640?apiTriggered=true&fromPk=7898989898"

方案2:接收JSON格式的单个params参数

如果需要将params作为单个参数传递JSON格式内容,可手动解析JSON字符串为Map:

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.*;

@PostMapping("/abc/aa/{type}")
private final ResponseEntity<Void> invoke(@PathVariable String type,
        @RequestParam(name = "params", required = false) String paramsJson) throws Exception {
    Map<String, Object> params = null;
    if (paramsJson != null) {
        ObjectMapper objectMapper = new ObjectMapper();
        params = objectMapper.readValue(paramsJson, Map.class);
    }
    // 业务逻辑处理
    return ResponseEntity.ok().build();
}

对应的Curl调用(Linux环境可直接用单引号包裹JSON避免转义):

curl -X POST 'http://localhost:8585/abc/aa/default_aa.TEST_varchar100_94946640?params={"apiTriggered":true,"fromPk":7898989898}'

内容的提问来源于stack exchange,提问作者vasu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 01:20:54