从 bash 脚本发送 POST 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53943485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 17:04:24  来源:igfitidea点击:

Sending POST Request from bash script

jsonbashhttp-post

提问by Bercovici Adrian

I want to execute a bashscript after i make a POSTrequest.So far i am using Postmanfor sending the request , but i was wondering if i can somehow do it from a bashscript as well with a jsonfile as parameter.

我想bash在发出POST请求后执行一个脚本。到目前为止,我正在使用它Postman来发送请求,但我想知道我是否可以从bash脚本以及将json文件作为参数以某种方式执行此操作。

I have looked into curlso far but it does not work:

curl到目前为止,我已经研究过,但它不起作用:

bash file

bash文件

curl -X POST -d req.json http://localhost:9500

Json file (req.json)

JSON 文件 ( req.json)

{
    "id":5,
    "name":"Dan",
    "age":33,
    "cnp":33,
    "children":100,
    "isMarried":0
}

I just get the error :

我只是收到错误:

HTTP/1.0 503 Service Unavailable

with the trailing HTML

与尾随 HTML

采纳答案by edaemon

curlshould do the job. This will send a normal POST request using the data in req.jsonas the body:

curl应该做的工作。这将使用数据req.json作为正文发送一个普通的 POST 请求:

curl -X POST -H "Content-Type: application/json" -d @req.json http://localhost:9500

The elements you were missing are -H "Content-Type: application/json"and the @in the data flag. Without the -Hflag as above curlwill send a content type of application/x-www-form-urlencoded, which most applications won't accept if they expect JSON. The @in the -dflag informs curlthat you are passing a file name; otherwise it uses the text itself (i.e. "req.json") as the data.

您缺少的元素是-H "Content-Type: application/json"@数据标志中的 。如果没有上述-H标志,curl将发送内容类型application/x-www-form-urlencoded,如果他们期望 JSON,大多数应用程序将不会接受。将@-d标志运筹学curl要传递一个文件名; 否则它使用文本本身(即“req.json”)作为数据。