如何使用 cURL 发布 JSON 数据?

问:

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

错误描述是这样的:

服务器拒绝此请求,因为请求实体的格式不受请求的方法 () 的请求资源支持。

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;
}

答1:

huntsbot.com提供全网独家一站式外包任务、远程工作、创意产品分享与订阅服务!

您需要将内容类型设置为 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 上,情况略有不同。请参阅评论线程。

huntsbot.com提供全网独家一站式外包任务、远程工作、创意产品分享与订阅服务!

对于 Windows,json 周围的单引号不起作用,我最终转义了双引号。 curl -X POST -H "Content-Type: application/json" -d "{ \"key1\": \"value1\" }" http://localhost:3000/api/method

对于 Windows 下的我,我需要使用这种格式 "{ """key1""": """value1""" }" 的引号来转义引号。还有这个答案:stackoverflow.com/questions/18314796/…

我遇到了 POST 请求的问题,但通过大写的“Application/json”解决了它,所以如果您收到 415 错误,请检查大写。

@Adam Tuttle 为什么你的评论有这么多赞成?在 ubuntu 14.04 上使用 curl,您需要 "Content-Type: application/json",而不仅仅是 "application/json"。这浪费了我很多时间...

@ostrokach 抱歉,它浪费了您的时间。当我发布它(没有重试)时,语法对我来说在 OSX 上运行良好。猜猜它是/只是平台差异。我想赞成票来自它帮助过的人。

答2:

huntsbot.com提供全网独家一站式外包任务、远程工作、创意产品分享与订阅服务!

尝试将您的数据放入文件中,例如 body.json,然后使用

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

您可能应该使用 --data-binary 选项而不是 --data。人们会期望客户端按原样发送数据,但 --data 从输入中去除 CR 和 LF。

使用带有内联 json 字符串的 cUrl 似乎是一场噩梦。需要转义双引号字符。使用这样的文件会更好。

请务必在文件名前添加 @ 字符,否则将不起作用。我只花了 20 分钟在这个垃圾上敲我的头......

这样,您还可以对文件运行 JSON lint 以查看解析 JSON 时是否有错误。

在 Windows 上,您需要在文件名“@body.json”两边加上双引号

答3:

huntsbot.com高效搞钱,一站式跟进超10+任务平台外包需求

对于 Windows,对 -d 值使用单引号对我不起作用,但在更改为双引号后它确实起作用。我还需要在大括号内转义双引号。

也就是说,以下内容不起作用:

curl -i -X POST -H "Content-Type: application/json" -d '{"key":"val"}' http://localhost:8080/appname/path

但以下工作:

curl -i -X POST -H "Content-Type: application/json" -d "{\"key\":\"val\"}" http://localhost:8080/appname/path

仅供参考 - 看起来你在 json 主体周围缺少一个结束双引号

对于 Windows 上的我来说,数据周围的 " 不起作用,没有引号起作用

如果您使用的是 PowerShell,请参阅 this 答案。

出于改进报价处理和许多其他原因,停止使用古老/弱 cmd.exe 并尝试改进的 shell 之一,例如来自 gitforwindows.org 站点的 Git-Bash。 (强烈推荐,即使你不使用 Git。)

答4:

一个优秀的自由职业者,应该有对需求敏感和精准需求捕获的能力,而huntsbot.com提供了这个机会

您可能会发现 resty 很有用:https://github.com/micha/resty

它是一个 CURL 的包装器,它简化了命令行 REST 请求。您将它指向您的 API 端点,它会为您提供 PUT 和 POST 命令。 (示例改编自主页)

$ resty http://127.0.0.1:8080/data #Sets up resty to point at your endpoing
$ GET /blogs.json                  #Gets http://127.0.0.1:8080/data/blogs.json
                                   #Put JSON
$ PUT /blogs/2.json '{"id" : 2, "title" : "updated post", "body" : "This is the new."}'
                                   # POST JSON from a file
$ POST /blogs/5.json < /tmp/blog.json

此外,通常仍然需要添加 Content Type 标头。不过,您可以这样做一次,以设置默认值,即为每个站点的每个方法添加配置文件:Setting default RESTY options

答5:

与HuntsBot一起,探索全球自由职业机会–huntsbot.com

它对我有用:

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。

答6:

huntsbot.com提供全网独家一站式外包任务、远程工作、创意产品分享与订阅服务!

https://i.stack.imgur.com/g8F0j.png

https://i.stack.imgur.com/fD0dp.png

笔记:

最新的 Postman 版本进行了一些 UI 升级,现在侧栏中提供了代码链接。

https://i.stack.imgur.com/7vOBG.png

最好的答案,节省了很多时间,谢谢:)

答7:

huntsbot.com洞察每一个产品背后的需求与收益,从而捕获灵感

例如,创建一个 JSON 文件 params.json,并将以下内容添加到其中:

[
    {
        "environment": "Devel",
        "description": "Machine for test, please do not delete!"
    }
]

然后你运行这个命令:

curl -v -H "Content-Type: application/json" -X POST --data @params.json -u your_username:your_password http://localhost:8000/env/add_server

专业提示:将此行添加到您的 ~/.curlrc 文件:--header Content-Type:Application/JSON

答8:

打造属于自己的副业,开启自由职业之旅,从huntsbot.com开始!

我只是遇到了同样的问题。我可以通过指定来解决它

-H "Content-Type: application/json; charset=UTF-8"

答9:

一个优秀的自由职业者,应该有对需求敏感和精准需求捕获的能力,而huntsbot.com提供了这个机会

这对我来说效果很好。

curl -X POST --data @json_out.txt http://localhost:8080/

在哪里,

-X 表示 http 动词。

–data 表示您要发送的数据。

-X POST 在此示例中是多余的

@SoftwareEngineer,但至少它对初学者有指导意义。

最好有透明但冗余的代码,而不是不透明的代码。我也更喜欢 --data 而不是 -d。这取决于团队对 Bash 的整体使用情况,但对于 Bash 初学者和不每天使用它的人来说绝对更容易。

答10:

huntsbot.com – 程序员副业首选,一站式外包任务、远程工作、创意产品分享订阅平台。

您可以使用 Postman 及其直观的 GUI 来组装您的 cURL 命令。

安装并启动 Postman 输入您的 URL、帖子正文、请求标头等。 pp. 单击代码 从下拉列表中选择 cURL 复制并粘贴您的 cURL 命令

注意:下拉列表中有几个用于自动生成请求的选项,这就是为什么我认为我的帖子首先是必要的。

没有意识到 Postman 中包含该功能。感谢您指出!

答11:

与HuntsBot一起,探索全球自由职业机会–huntsbot.com

HTTPie 是 curl 的推荐替代品,因为您可以这样做

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

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

Some-Header:value

对于标题,和

name==value

用于查询字符串参数。如果你有大量数据,你也可以从一个文件中读取它,并对其进行 JSON 编码:

 field=@file.txt

我祈祷这是一个标准 - 至少在每台服务器上可用/预安装方面。

此外,如果 httpie 支持溢出 curl 格式的命令,那将是很好的,以应对 httpie 在特定主机上不可用的情况。

原文链接:https://www.huntsbot.com/qa/Dk66/how-do-i-post-json-data-with-curl?lang=zh_CN&from=csdn

huntsbot.com高效搞钱,一站式跟进超10+任务平台外包需求

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Curl是一个非常流行的命令行工具和库,可用于传输数据,其中包括使用HTTP协议发送和接收数据。如果你想要使用Curl发送JSON数据,可以按照以下步骤操作: 1. 准备好要发送的JSON数据,将其保存为字符串或从文件中读取。例如,以下是一个JSON字符串: ``` {"name": "John Smith", "age": 30, "city": "New York"} ``` 2. 使用Curl库中的curl_easy_init()函数初始化Curl句柄。 ``` CURL *curl; curl = curl_easy_init(); ``` 3. 设置请求的URL地址。例如: ``` curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/api"); ``` 4. 设置请求的HTTP方法,这里我们使用POST方法。 ``` curl_easy_setopt(curl, CURLOPT_POST, 1L); ``` 5. 设置请求头,指定Content-Type为application/json。 ``` struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "Content-Type: application/json"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); ``` 6. 设置请求体,将JSON数据作为请求体发送。 ``` curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "{\"name\": \"John Smith\", \"age\": 30, \"city\": \"New York\"}"); ``` 7. 执行HTTP请求,将响应保存在一个缓冲区中。 ``` CURLcode res; char *response = NULL; size_t response_size = 0; curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_memory_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&response); res = curl_easy_perform(curl); ``` 8. 处理响应数据。在这里,我们将响应数据打印出来。 ``` printf("%s\n", response); ``` 9. 释放Curl句柄和请求头。 ``` curl_easy_cleanup(curl); curl_slist_free_all(headers); ``` 完整的代码示例如下: ``` #include <stdio.h> #include <curl/curl.h> size_t write_memory_callback(void *ptr, size_t size, size_t nmemb, void *data) { size_t realsize = size * nmemb; char **mem = (char **)data; *mem = realloc(*mem, response_size + realsize + 1); if (*mem == NULL) { printf("out of memory\n"); return 0; } memcpy(*mem + response_size, ptr, realsize); response_size += realsize; (*mem)[response_size] = 0; return realsize; } int main(void) { CURL *curl; CURLcode res; char *response = NULL; size_t response_size = 0; curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/api"); curl_easy_setopt(curl, CURLOPT_POST, 1L); struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "Content-Type: application/json"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "{\"name\": \"John Smith\", \"age\": 30, \"city\": \"New York\"}"); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_memory_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&response); res = curl_easy_perform(curl); if (res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } else { printf("%s\n", response); } curl_slist_free_all(headers); curl_easy_cleanup(curl); free(response); } curl_global_cleanup(); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值