如何用Curl从终端/命令行向Test Spring REST发送JSON数据?

我使用Ubuntu并在其上安装了cURL。我想用cURL来测试我的Spring REST应用程序。我在Java端写了我的POST代码。然而,我想用cURL来测试它。我试图发布一个JSON数据。示例数据是这样的。

{"value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true}

我使用这个命令。

curl -i \
    -H "Accept: application/json" \
    -H "X-HTTP-Method-Override: PUT" \
    -X POST -d "value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true \
    http://localhost:8080/xx/xxx/xxxx

它返回这个错误。

HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 1051
Date: Wed, 24 Aug 2011 08:50:17 GMT

错误描述是这样的。

*服务器拒绝了这个请求,因为请求实体的格式不受所请求的资源对所请求的方法的支持()。

Tomcat日志。 "POST /ui/webapp/conf/clear HTTP/1.1" 415 1051

cURL命令的正确格式是什么?

这是我的Java端PUT代码(我已经测试了GET和DELETE,它们都能工作)。

@RequestMapping(method = RequestMethod.PUT)
public Configuration updateConfiguration(HttpServletResponse response, @RequestBody Configuration configuration) { //consider @Valid tag
    configuration.setName("PUT worked");
    //todo If error occurs response.sendError(HttpServletResponse.SC_NOT_FOUND);
    return configuration;
}
对该问题的评论 (2)
解决办法

你需要将你的内容类型设置为application/json。但是-d发送的内容类型是application/x-www-form-urlencoded,Spring'方面不接受。

看一下curl man page,我认为你可以使用-H

-H "Content-Type: application/json"

完整的例子。

curl --header "Content-Type: application/json" \
  --request POST \
  --data '{"username":"xyz","password":"xyz"}' \
  http://localhost:3000/api/login

("H "是 "头 "的缩写,"D "是 "数据 "的缩写)

请注意,如果你使用-d-request POST是*可选的,因为-d标志意味着是POST请求。


在Windows上,情况略有不同。见评论线。

评论(26)

试着把你的数据放在一个文件里,例如body.json,然后用

curl -H "Content-Type: application/json" --data @body.json http://localhost:8080/ui/webapp/conf
评论(10)

你可能会发现resty有用。 https://github.com/micha/resty

它是一个CURL的封装器,可以简化命令行REST请求。 你把它指向你的API端点,它就会给你PUT和POST命令。 (例子来自主页)

$ resty http://127.0.0.1:8080/data #Sets up resty to point at your endpoing
$ GET /blogs.json                  #Gets http://127.0.0.1:8080/data/blogs.json
                                   #Put JSON
$ PUT /blogs/2.json '{"id" : 2, "title" : "updated post", "body" : "This is the new."}'
                                   # POST JSON from a file
$ POST /blogs/5.json < /tmp/blog.json

另外,往往还需要添加Content Type头文件。 不过你可以做一次,设置一个默认的,每个方法每个站点添加配置文件。 [设置默认RESTY选项][1]

[1]: https://github.com/micha/resty#setting-the-default-curl-options "设置默认的RESTY选项&quot。

评论(0)

对于Windows来说,对"-d "值使用单引号对我来说是行不通的,但改成双引号后就可以了。 另外,我需要在大括号内转义双引号。

也就是说,下面的内容无法使用。

curl -i -X POST -H "Content-Type: application/json" -d '{"key":"val"}' http://localhost:8080/appname/path

但下面的工作。

curl -i -X POST -H "Content-Type: application/json" -d "{\"key\":\"val\"}" http://localhost:8080/appname/path
评论(3)

我使用的时候就能用。

curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"id":100}' http://localhost/api/postJsonReader.do

它被愉快地映射到Spring控制器上。

@RequestMapping(value = "/postJsonReader", method = RequestMethod.POST)
public @ResponseBody String processPostJsonData(@RequestBody IdOnly idOnly) throws Exception {
        logger.debug("JsonReaderController hit! Reading JSON data!"+idOnly.getId());
        return "JSON Received";
}

IdOnly是一个简单的带有id属性的[POJO][1]。

[1]: http://en.wikipedia.org/wiki/Plain_Old_Java_Object

评论(0)

例如,创建一个JSON文件params.json,并添加以下内容。

[
    {
        "environment": "Devel",
        "description": "Machine for test, please do not delete!"
    }
]

然后你运行这个命令。

curl -v -H "Content-Type: application/json" -X POST --data @params.json -u your_username:your_password http://localhost:8000/env/add_server
评论(0)

这对我很有效。

curl -X POST --data @json_out.txt http://localhost:8080/

哪儿:

-X表示http动词。

--data表示你要发送的数据。

评论(1)

我只是遇到了同样的问题。我可以通过指定以下方式解决这个问题

-H "Content-Type: application/json; charset=UTF-8"
评论(0)

使用CURL Windows,试试这个。

curl -X POST -H "Content-Type:application/json" -d "{\"firstName\": \"blablabla\",\"lastName\": \"dummy\",\"id\": \"123456\"}" http-host/_ah/api/employeeendpoint/v1/employee
评论(0)

你可以使用[Postman][1],用它直观的GUI来组装你的cURL命令。

  1. 安装并启动Postman
  2. 输入你的URL、Post Body、Request Headers等。 pp. 2.点击 "代码"。

  3. 从下拉列表中选择 "cURL"。

  4. 复制& 粘贴你的cURL命令

  • 注:在下拉列表中,有几个自动生成请求的选项,这就是为什么我认为我的帖子是必要的。 在下拉列表中,有几个自动生成请求的选项,这就是为什么我首先认为我的帖子是必要的。

[1]:

评论(1)

[HTTPie][1]是推荐的 "curl "的替代品,因为你可以只做

$ http POST http://example.com/some/endpoint name=value name1=value1

它默认使用JSON语言,并将为你设置必要的头,以及将数据编码为有效的JSON。 还有

Some-Header:value

的标题,以及

name==value

为查询字符串参数。 如果你有一大块数据,你也可以从文件中读取数据,并对其进行JSON编码。

 field=@file.txt

[1]: https://httpie.org/

评论(0)

如果你正在针对RESTful接口测试大量的JSON发送/响应,你可能想看看Chrome浏览器的Postman插件(它允许你手动定义Web服务测试)及其基于Node.js的Newman命令行伙伴(它允许你针对"集合&quot.的Postman测试进行自动测试。)两者都是免费和开放的。 的Postman测试。)都是免费和开放的。

评论(0)

你也可以把你的JSON内容放在一个文件中,然后通过标准输入使用--file-upload选项把它传递给curl,就像这样。

 echo 'my.awesome.json.function({"do" : "whatever"})' | curl -X POST "http://url" -T -
评论(0)

这对我来说很有效,另外使用BASIC认证。

curl -v --proxy '' --basic -u Administrator:password -X POST -H "Content-Type: application/json"
        --data-binary '{"value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true}'
        http://httpbin.org/post

当然,在没有SSL和检查证书的情况下,你绝对不能使用BASIC认证。

今天我又遇到了这个问题,使用Cygwin's cURL 7.49.1 for Windows...。 当使用"--数据 "或"--数据二进制 "作为JSON参数时,cURL会感到困惑,并将JSON中的"{}"解释为URL模板。 增加一个-g参数来关闭cURL的globbing就解决了这个问题。

另见https://stackoverflow.com/questions/8333920/passing-a-url-with-brackets-to-curl

评论(0)

这对我很有效。

curl -H "Content-Type: application/json" -X POST -d @./my_json_body.txt http://192.168.1.1/json
评论(0)

你可以用postman转换成CURL[![在此输入图片描述][1]][1] 。

[![在此输入图像描述][2]][2]

[1]: https://i.stack.imgur.com/g8F0j.png [2]: https://i.stack.imgur.com/fD0dp.png

评论(1)

我是用下面的格式用Web服务器测试的。

use -F 'json data'

让'我们假设这种JSON dict格式。

{
    'comment': {
        'who':'some_one',
        'desc' : 'get it'
    }
}

Full example

curl -XPOST your_address/api -F comment='{"who":"some_one", "desc":"get it"}'
评论(0)

在Windows10上,这对我是有效的

curl -d "{"""所有者"":"""sasdasdasd"""}"
-H "Content-Type:
application/json"
-X PUT http://localhost:8080/api/changeowner/CAR4
评论(0)

使用-d选项来添加有效载荷

curl -X POST \
http://:/<path> \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"foo": "bar",
"lorem": "ipsum"
}'

此外。

使用-X POST来使用POST方法。

使用 -H '接受。 application/json' 添加接受类型头

使用 -H '内容类型。 application/json' 添加内容类型头

评论(0)

请检查这个[工具][1]。 它可以帮助你轻松创建curl片段。

curl -XGET -H "Accept: application/json" -d "{\"value\":\"30\",\"type\":\"Tip 3\",\"targetModule\":\"Target 3\",\"configurationGroup\":null,\"name\":\"Configuration Deneme 3\",\"description\":null,\"identity\":\"Configuration Deneme 3\",\"version\":0,\"systemId\":3,\"active\":true}" "http://localhost:8080/xx/xxx/xxxx"

[1]: https://pranayrauthu.github.io/fetcher/#/curl

评论(0)