【问题标题】:how to call an endpoint that accepts only string value as request body parameter如何调用仅接受字符串值作为请求正文参数的端点
【发布时间】:2019-07-16 14:13:02
【问题描述】:

我已经定义了一个接受字符串值作为请求主体参数的方法,如下所示

@RequestMapping(value="/stringParam",method=RequestMethod.POST,consumes=MediaType.TEXT_PLAIN)
    public String stringMethod(@RequestBody String stringParam){

        return stringParam;
    }

我尝试使用以下 curl 命令调用该端点

curl -X POST  "http://localhost:7979/choudhury-rest/rest/book/stringParam" -d '\"ravi\"' -H "Content-Type: application/json"

这给了我这个错误

The request sent by the client was syntactically incorrect.

之后,我尝试了另一种方式

curl -X POST  "http://localhost:7979/choudhury-rest/rest/book/stringParam" -d 'stringParam=\"ravi\"' -H "Content-Type: application/json"

这也给了我这个错误

The request sent by the client was syntactically incorrect.

谁能帮助我如何调用该方法(我不知道我们是否可以定义一个接受原始值(int、long 等)作为请求主体参数的 rest 方法)

【问题讨论】:

  • 尝试用{ 括起您的数据,并用: 替换= 例如:-d '{"stringParam":"ravi"}'
  • “我不知道我们是否可以定义一个接受原始值作为请求主体参数的 rest 方法” - String 在 Java 中不是原始类型。

标签: java spring web-services curl postman


【解决方案1】:

我发现您可以更改几件事来完成这项工作。

您必须更改控制器中的消耗参数,使用 MediaType.TEXT_PLAIN_VALUE 而不是 MediaType.TEXT_PLAIN

@RequestMapping(value="/stringParam", method=RequestMethod.POST, consumes=MediaType.TEXT_PLAIN_VALUE)
public String stringMethod(@RequestBody String stringParam){
    return stringParam;
}

使用 curl 时,通过包含标题 Content-Type: text/plain 来定义您仅发送文本

$ curl -X POST  "http://localhost:8080/choudhury-rest/rest/book/stringParam" -d "ravi" -H "Content-Type: text/plain"

结果

$ curl -X POST  "http://localhost:8080/choudhury-rest/rest/book/stringParam" -d "ravi" -H "Content-Type: text/plain"
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100     8  100     4  100     4   4000   4000 --:--:-- --:--:-- --:--:--  8000ravi

干杯!

注意:我在 SpringBoot v2.0.5.RELEASE 中测试了这个控制器

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2017-09-20
    • 1970-01-01
    相关资源
    最近更新 更多