如何使用Curl从终端/命令行发布JSON数据以测试Spring REST? [英] How do I POST JSON data with Curl from a terminal/commandline to Test Spring REST?
问题描述
我使用Ubuntu,并在其上安装 cURL .我想用cURL测试我的Spring REST应用程序.我在Java端编写了POST代码.但是,我想用cURL对其进行测试.我正在尝试发布JSON数据.示例数据如下:
I use Ubuntu and installed cURL on it. I want to test my Spring REST application with cURL. I wrote my POST code at the Java side. However, I want to test it with cURL. I am trying to post a JSON data. Example data is like this:
{"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
Tomcat log: "POST /ui/webapp/conf/clear HTTP/1.1" 415 1051
cURL命令的正确格式是什么?
What is the right format of the cURL command?
这是我的Java端PUT
代码(我已经测试了GET和DELETE并且它们可以工作):
This is my Java side PUT
code (I have tested GET and DELETE and they work):
@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;
}
推荐答案
您需要将内容类型设置为application/json.但是 -d
发送内容类型application/x-www-form-urlencoded
,但不是在春天那边被接受了.
You need to set your content-type to application/json. But -d
sends the Content-Type application/x-www-form-urlencoded
, which is not accepted on Spring's side.
Looking at the curl man page, I think you can use -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
是--header
的缩写,-d
是--data
的缩写)
(-H
is short for --header
, -d
for --data
)
请注意,如果您使用-d
,则-request POST
是可选,因为-d
标志表示POST请求.
Note that -request POST
is optional if you use -d
, as the -d
flag implies a POST request.
在Windows上,情况略有不同.请参阅评论主题.
On Windows, things are slightly different. See the comment thread.
这篇关于如何使用Curl从终端/命令行发布JSON数据以测试Spring REST?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!