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

查看:48
本文介绍了如何使用 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;
}

推荐答案

你需要将你的 content-type 设置为 application/json.但是 -d (或 --data) 发送 Content-Type application/x-www-form-urlencoded,Spring 这边不接受.

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

查看 curl 手册页,我认为您可以使用 -H(或--header):

Looking at the curl man page, I think you can use -H (or --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 的缩写)

(-H is short for --header, -d for --data)

请注意,如果您使用 -d-request POST可选,正如 -d 标志所暗示的那样POST 请求.

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天全站免登陆