[英]How to send JSON file as part of request body in CURL POST command
I am using CURL command line to send HTTP POST to a web service.我正在使用 CURL 命令行将 HTTP POST 发送到 Web 服务。 I want to include a file's contents as a PART of the body of the POST command.
我想包括文件的内容作为POST指令的身体的一部分。 Is this possible?
这可能吗? I know I can send a file as the entire body as answered here .
我知道我可以按照此处的回答将文件作为整个正文发送。 But I only want a part of the body to be the content of the file.
但我只希望正文的一部分成为文件的内容。
For example例如
curl -d '{ "name": "rahul", "speed": "fast", "data": { "number": 1, "letter": "abd", "letter2": "efg"} }' 'http://...'
Here I only want data
as the file's content.这里我只想要
data
作为文件的内容。 Not the entire body.不是整个身体。 How can I do this?
我怎样才能做到这一点?
Set a variable to contain the file contents:设置一个变量来包含文件内容:
data=$(cat /path/to/file)
then substitute it into the JSON:然后将其替换为 JSON:
curl -d '{ "name": "rahul", "speed": "fast", "data": "'$data'" }' 'http://...'
You accepted @Barmar's answer, but for anyone reading this, @Barmar switched the double- and single-quotes, which will cause the command to not work as intended.您接受了@Barmar 的回答,但是对于阅读本文的任何人,@Barmar 切换了双引号和单引号,这将导致命令无法按预期工作。
The following works:以下工作:
data=$(cat filename) && \
curl -d '{ "name": "rahul", "speed": "fast", "data": "'$data'" }' 'http://...'
Notice that the $data
variable is surrounded by single-quotes first, then double-quotes.请注意,
$data
变量首先被单引号包围,然后被双引号包围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.