如何使用cURL发布JSON数据? [英] How do I POST JSON data with cURL?

查看:126
本文介绍了如何使用cURL发布JSON数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Ubuntu,并在其上安装了 cURL 。我想用cURL测试我的Spring REST应用程序。我在Java端编写了POST代码。但是,我想用cURL对其进行测试。我正在尝试发布JSON数据。示例数据如下:

I use Ubuntu and installed cURL on it. I want to test my Spring REST application with cURL. I wrote my POST code at the Java side. However, I want to test it with cURL. I am trying to post a JSON data. Example data is like this:

{"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

Tomcat log: "POST /ui/webapp/conf/clear HTTP/1.1" 415 1051

cURL命令的正确格式是什么?

What is the right format of the cURL command?

这是我的Java端 PUT 代码(我已经测试过GET和DELETE并且它们可以工作):

This is my Java side PUT code (I have tested GET and DELETE and they work):

@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端不接受。

You need to set your content-type to application/json. But -d sends the Content-Type application/x-www-form-urlencoded, which is not accepted on Spring's side.

查看卷曲手册页,我认为您可以使用 -H

Looking at the curl man page, I think you can use -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 很短对于-标题 -d 对于-data

请注意,如果您使用<$ c $,则-请求POST 可选 c> -d ,如 -d 标志i

Note that -request POST is optional if you use -d, as the -d flag implies a POST request.

在Windows上,情况略有不同。参见评论主题。

On Windows, things are slightly different. See the comment thread.

这篇关于如何使用cURL发布JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆