json - 如何使用 cURL 发布 JSON 数据?

标签 json rest spring-mvc curl http-headers

我使用 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/

相关文章:

php - MYSQL触发器中如何解析JSON

c# - 使用 Hammock .net 网络库发出 LinkedIn API 请求

json - ExtJS JSON和Grails

python - OpenCV(在 C++ 中)到 MQTT 代理

java - REST/jersey 和 JSON 的问题

Laravel API 响应对象格式化

javascript - Spring MVC + Javascript

spring-mvc - 使用 angularjs 开发的应用程序中 ie 9/10 上的数据未更新

java - web.servlet.PageNotFound ,请求方法 'GET' 不支持,Spring

json - Excel VBA : Parsed JSON Object Loop