如何使用 cURL 发布 JSON 数据?

问题描述

您需要将内容类型设置为 application/json。但是-d(或--data)发送 Content-Type application/x-www-form-urlencoded,这在 Spring 方面是不被接受的。

查看curl 手册页,我认为您可以使用-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

请注意,如果您使用,这-request POST可选-d的,因为该-d标志意味着 POST 请求。


在 Windows 上,情况略有不同。请参阅评论线程。

解决方法

我使用 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","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;
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...