我使用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并且它们可以工作):
PUT
@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发送Content-Type application/x-www-form-urlencoded,在Spring方面不接受。
-d
application/x-www-form-urlencoded
查看curl手册页,我认为您可以使用-H:
-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)
--header
--data
请注意,如果使用,-request POST则是 可选的-d,因为该-d标志表示POST请求。
-request POST
在Windows上,情况略有不同。请参阅评论主题。