我使用 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
错误描述是这样的:
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().
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;
}
最佳答案
您需要将您的内容类型设置为 application/json。但是-d
(或 --data
)发送 Content-Type application/x-www-form-urlencoded
,Spring 这边不接受。
看curl man page , 我想你可以使用 -H
(或--header
):
-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
的缩写)
请注意,如果您使用 -d
,-request POST
是 可选,正如 -d
标志所暗示的那样POST 请求。
在 Windows 上,情况略有不同。请参阅评论线程。
关于json - 如何使用 cURL 发布 JSON 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7172784/