我使用Ubuntu并在上面安装了cURL。我想用cURL测试我的SpringREST应用程序。我在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/clearHTTP/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;
}

当前回答

您还可以将JSON内容放入文件中,并通过标准输入使用--uploadfile选项将其传递给curl,如下所示:

echo 'my.awesome.json.function({"do" : "whatever"})' | curl -X POST "http://url" -T -

其他回答

HTTPie是卷曲的推荐替代品,因为你可以

http POST http://example.com/some/endpoint name=value name1=value1

默认情况下,它使用JSON,并将处理为您设置必要的标头以及将数据编码为有效的JSON。还有:

Some-Header:value

对于标头,以及

name==value

查询字符串参数。如果你有一大块数据,你也可以从一个JSON编码的文件中读取:

field=@file.txt

它对我有用,使用:

curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"id":100}' http://localhost/api/postJsonReader.do

它很高兴地映射到Spring控制器:

@RequestMapping(value = "/postJsonReader", method = RequestMethod.POST)
public @ResponseBody String processPostJsonData(@RequestBody IdOnly idOnly) throws Exception {
        logger.debug("JsonReaderController hit! Reading JSON data!"+idOnly.getId());
        return "JSON Received";
}

IdOnly是一个具有id属性的简单POJO。

-H在标头中发送类似内容类型或身份验证令牌的内容-d此处添加您的数据最后添加站点链接

注意:不要忘记为身份验证凭据添加身份验证令牌(如果有)

curl -X POST -H 'Content-Type: application/json' -H 'Authorization: Token 2de403987713595a7955a9b4655b9e206d4294b3' -d '{"title":"Post test with curl", "body": "test body"}' http://127.0.0.1:8000/api/v1/feeds/

尝试将数据放在一个文件中,比如body.json,然后使用

curl -H "Content-Type: application/json" --data @body.json http://localhost:8080/ui/webapp/conf

简单的是

curl -X POST https://localhost:3000/ 
   -H "Content-Type: application/json"
   -d '{"productId": 123456, "quantity": 100}'