如何通过 Windows 批处理脚本中的 curl 发送带有 json 正文的 POST 请求

Posted

技术标签:

【中文标题】如何通过 Windows 批处理脚本中的 curl 发送带有 json 正文的 POST 请求【英文标题】:How to send POST request with json body via curl from windows batch script 【发布时间】:2017-08-05 10:45:03 【问题描述】:

我正在编写批处理脚本,它应该使用 json 发送请求。

call curl -X POST -H 'Content-type: application/json' --data '"text": "Pull requests:\n%linksText% has been deployed to %stagingServerUrl%", "username": "Staging Server"' http://requestb.in/ovehwtov

我从 git bash 运行我的脚本,虽然它发送了请求,但正文格式错误,就在它发送请求之前,我在控制台中看到错误:

curl: (6) Couldn't resolve host 'application'
curl: (6) Couldn't resolve host '"Pull'
curl: (6) Couldn't resolve host 'requests:\nhttp'
curl: (6) Couldn't resolve host 'has'
curl: (6) Couldn't resolve host 'been'
curl: (6) Couldn't resolve host 'deployed'
curl: (6) Couldn't resolve host 'to'
curl: (6) Couldn't resolve host 'unicorns2url",'
curl: (6) Couldn't resolve host '"username"'
curl: (6) Couldn't resolve host 'Staging'
curl: (3) [globbing] unmatched close brace/bracket in column 8
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    11    0     2  100     9      6     30 --:--:-- --:--:-- --:--:--    30ok

这是身体的样子:

'"text":

这是不对的。

如您所见,我正在从变量中组合 json,但这不是失败的原因:当我删除它们并调用时

call curl -X POST -H 'Content-type: application/json' --data '"text": "Pull requests has been deployed to", "username": "Staging Server"' http://requestb.in/ovehwtov

同样的错误发生了。

但是,当我从批处理脚本中复制此命令并将其直接粘贴到 git bash 控制台时,它可以无缝运行。不要问我为什么要从 git bash 运行 windows 批处理脚本,因为我可以使用 bash 语言编写 bash 脚本,而不是使用笨拙和令人困惑的 DOS 语法。当我开始编写脚本并且几乎完成时,我没有意识到这一点(除了这部分)。如何让它发挥作用?谢谢!

【问题讨论】:

在 cmd 解释的命令中,包含空格的标记需要用双引号括起来。试试call curl -X POST -H "Content-type: application/json" --data "'text': 'Pull requests:\n%linksText% has been deployed to %stagingServerUrl%', 'username': 'Staging Server'" http://requestb.in/ovehwtov 谢谢你,好先生。虽然json中不允许单引号,所以应该是call curl -X POST -H "Content-type: application/json" --data "\"text\": \"Pull requests:\n%linksText% has been deployed to %stagingServerUrl%\", \"username\": \"Staging Server\"" http://requestb.in/qkebavqk 【参考方案1】:

试试:

curl -X POST -H "Content-type: application/json" --data "\"text\": \"Pull requests has been deployed to\", \"username\": \"Staging Server\"" http://requestb.in/ovehwtov

显然有正确的数据。

如果您使用的是 Windows,则必须使用“\”。

【讨论】:

以上是关于如何通过 Windows 批处理脚本中的 curl 发送带有 json 正文的 POST 请求的主要内容,如果未能解决你的问题,请参考以下文章

将 curl 输出存储在变量批处理脚本中

如何通过批处理脚本下载JRE包

如何在bash脚本中执行存储在heredoc中的curl命令?

如何通过批处理脚本检查可用内存(RAM)?

git-bash 中的 curl 命令

使用 Windows 任务调度程序和 xampp 服务器运行带有 curl 的 php 脚本