[英]Post a JSON file to a URL using Shell Script
I am writing a shell script to post a JSON file to a URL. 我正在编写一个Shell脚本以将JSON文件发布到URL。
The header is: 标头是:
Content-Type: application/json
Accept: application/json
Account-Number: xxxxxxxx
Authorization: Basic eW91cl91c2VyX25hbWU6cGFzc3dvcmQ=
The above JSON string is saved into a .JSON file and my curl command should process it and get the desired response. 上面的JSON字符串被保存到.JSON文件中,我的curl命令应该对其进行处理并获得所需的响应。 I use the following command but it does not process successfully:
我使用以下命令,但无法成功处理:
curl -H "Content-Type: application/json" -X POST -d "data=@$f" https://abcdef.com/test/example/v1/
$f has the JSON file name. $ f具有JSON文件名。
I have the following questions as well: 我也有以下问题:
You're not sending all the headers. 您没有发送所有标题。 I don't believe there's an option to read the desired headers from a file.
我不相信有一个选项可以从文件中读取所需的标头。
Since you're scripting in bash, I'd store all the options in a shell array for readability: 由于您使用bash编写脚本,因此为了可读性,我将所有选项存储在shell数组中:
curl_opts=(
-H "Content-Type: application/json"
-H "Accept: application/json"
-H "Account-Number: xxxxxxxx"
-H "Authorization: Basic eW91cl91c2VyX25hbWU6cGFzc3dvcmQ="
-X POST
--data-binary "@$f"
)
curl "${curl_opts[@]}" https://abcdef.com/test/example/v1/
Assuming you want to post your JSON data exactly as-is (without further processing), you should use --data-binary
. 假设您想按原样发布JSON数据(无需进一步处理),则应使用
--data-binary
。 If preserving content like newlines is not necessary, you can use -d
/ --data
, but in the form -d @file
, like this: 如果不需要保留换行符之类的内容,则可以使用
-d
/ --data
,但格式为-d @file
,如下所示:
filename=file.json
curl http://httpbin.org/post --data-binary "@$filename" --user "name:password" -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Account-Number: xxxxxxxx'
of course, after fixing all syntax errors you have in your JSON (like hanging commas, isolated single quotes, etc). 当然,修复了JSON中存在的所有语法错误后(例如挂逗号,孤立的单引号等)。 Specifying data in form
key=val
(or key=@file
), like you're trying, will not work (you can use it for form parameters with -F
, though); 就像您尝试的那样,以
key=val
(或key=@file
)形式指定数据将不起作用(不过,您可以将其用于-F
形式参数); see valid data part syntax in curl . 在curl中查看有效的数据部分语法 。
Note that when using --data-binary
, default method is POST
(so, no need to specify it with -X
), but you'll have to specify the correct Content-Type
. 请注意,在使用
--data-binary
,默认方法是POST
(因此,无需使用-X
进行指定),但是您必须指定正确的Content-Type
。
Also, instead of manually calculating Authorization
header for HTTP Basic Auth, just use the -u
/ --user <user:pass>
option. 另外,不要手动为HTTP Basic Auth计算
Authorization
标头,而只需使用-u
/ --user <user:pass>
选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.