bash 如何使用curl将带空格的字符串作为http POST数据传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20733561/
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 09:04:10  来源:igfitidea点击:

How to pass a string with spaces as http POST data using curl

perlbashcurlhttp-post

提问by tzippy

I am running a perl script that calls a bash script with arguments. It reads a string from a socket, splits it and saves it to an array. This is how such a string looks:

我正在运行一个 perl 脚本,它使用参数调用 bash 脚本。它从套接字读取字符串,将其拆分并将其保存到数组中。这是这样一个字符串的样子:

  22.12.13 20:21:12;RING;0

The first array element is a date, which is passed as an argument to a bash script. In the bash script, the arguments are passed on to curl as POST data.

第一个数组元素是日期,它作为参数传递给 bash 脚本。在 bash 脚本中,参数作为 POST 数据传递给 curl。

I don't know how to handle the space between date and time in the string. The curl is executed correctly and the server responds with OK (200). However it's only the first part (up to the space) that is passed as POST data. The time is missing. curl gives the folowing error:

我不知道如何处理字符串中日期和时间之间的空格。curl 正确执行,服务器响应 OK (200)。然而,它只是作为 POST 数据传递的第一部分(直到空格)。时间不见了。curl 给出了以下错误:

curl: (6) Couldn't resolve host '20:21'

These are the relevant lines from the scripts:

这些是脚本中的相关行:

     #perl script
     my $EXTPRO="/path/to/script.sh"; 
if ($_ =~ /RING/){ 
     my @C = split(/;/); 
     my @args = ($EXTPRO, $nr, $C[0], "String"); 
     system(@args);


#bash script:
curl http://url.com/add -F foo= -F date= -F foobar=

回答by Miller

The time is being passed correctly, it's just your bash script that needs to be edited as your error reflects.

时间正在正确传递,只是您的 bash 脚本需要根据您的错误进行编辑。

curl http://url.com/add -F foo=String -F date=22.12.13 20:21:12 -F foobar=Fake_NR_Data

The time is being treated as a second URL. To get your bash to work correctly, just enclose $2 in quotes

时间被视为第二个 URL。为了让您的 bash 正常工作,只需将 $2 括在引号中

#bash script:
curl http://url.com/add -F foo= -F date="" -F foobar=

回答by Patrice M.

@Miller 's answer is fine. My own preference is to use double-quotes for simple, predictable values, and a temp file for anything else, in particular for dynamic JSON data:

@Miller 的回答很好。我自己的偏好是对简单的、可预测的值使用双引号,对其他任何东西使用临时文件,特别是对于动态 JSON 数据:

 echo $json_data > data1.json
 [curl -X POST --data-urlencode "foo=" --data-urlencode "date=" --data-urlencode [email protected]

Otherwise, spaces, quotes and all create major headaches on the bash command line, and result in troubleshooting being extra hard. data1.json contains the exact data, before urlencoding.

否则,空格、引号和所有这些都会在 bash 命令行上造成令人头疼的问题,并导致故障排除更加困难。data1.json 包含 urlencoding 之前的确切数据。