如何使用cURL发送带有正文,标头和HTTP参数的POST?


39

我找到了很多有关如何在cURL中使用简单POST命令的示例,但没有找到有关如何发送完整的HTTP POST命令的示例,其中包括:

  • 标头(基本身份验证)
  • HTTP参数(s=1&r=33
  • 正文数据,一些XML字符串

我发现的是:

echo "this is body" | curl -d "ss=ss&qq=11" http://localhost/

那是行不通的,它将HTTP参数作为正文发送。



感觉像是对superuser.com/questions/149329/可能欺骗 。我通常不会将这样一个古老的热门问题标记为欺骗,但这是一个例外。为了完整性,可能需要移走一些东西。
Michael Durrant 2015年

实际上,另一个答案非常明确地提到了--header这一点,而这个答案并未提及
Michael Durrant

Answers:


15

声誉不足,无法发表评论,因此请留下答案以希望有所帮助。

curl -L -v --post301 --post302 -i -X PUT -T "${aclfile}"  \
  -H "Date: ${dateValue}" \
  -H "Content-Type: ${contentType}" \
  -H "Authorization: AWS ${s3Key}:${signature}" \
  ${host}:${port}${resource}

这就是我用于S3存储桶acl put操作的内容。标题位于-H中,而作为XML文件的主体位于-T之后的$ {aclfile}中。您可以从输出中看到:

/aaa/?acl
* About to connect() to 192.168.57.101 port 80 (#0)
*   Trying 192.168.57.101...
* Connected to 192.168.57.101 (192.168.57.101) port 80 (#0)
> PUT /aaa/?acl HTTP/1.1
> User-Agent: curl/7.29.0
> Host: 192.168.57.101
> Accept: */*
> Date: Thu, 18 Aug 2016 08:01:44 GMT
> Content-Type: application/x-www-form-urlencoded; charset=utf-8
> Authorization: AWS WFBZ1S6SO0DZHW2LRM6U:r84lr/lPO0JCpfk5M3GRJfHdUgQ=
> Content-Length: 323
> Expect: 100-continue
>
< HTTP/1.1 100 CONTINUE
HTTP/1.1 100 CONTINUE

* We are completely uploaded and fine
< HTTP/1.1 200 OK
HTTP/1.1 200 OK
< x-amz-request-id: tx00000000000000000001f-0057b56b69-31d42-default
x-amz-request-id: tx00000000000000000001f-0057b56b69-31d42-default
< Content-Type: application/xml
Content-Type: application/xml
< Content-Length: 0
Content-Length: 0
< Date: Thu, 18 Aug 2016 08:01:45 GMT
Date: Thu, 18 Aug 2016 08:01:45 GMT

<
* Connection #0 to host 192.168.57.101 left intact

如果url参数包含特殊符号(例如“ +”),请对每个参数(包含特殊符号)使用--data-urlencode:

curl -G -H "Accept:..." -H "..." --data-urlencode "beginTime=${time}+${zone}" --data-urlencode "endTime=${time}+${zone}" "${url}"

57

HTTP“参数”是URL的一部分:

"http://localhost/?name=value&othername=othervalue"

基本身份验证有一个单独的选项,无需创建自定义标头:

-u "user:password"

POST“正文”可以通过--data(for application/x-www-form-urlencoded)或--form(for multipart/form-data)发送:

-F "foo=bar"                  # 'foo' value is 'bar'
-F "foo=<foovalue.txt"        # the specified file is sent as plain text input
-F "foo=@foovalue.txt"        # the specified file is sent as an attachment

-d "foo=bar"
-d "foo=<foovalue.txt"
-d "foo=@foovalue.txt"
-d "@entirebody.txt"          # the specified file is used as the POST body

--data-binary "@binarybody.jpg"

因此,总结一下:

curl -d "this is body" -u "user:pass" "http://localhost/?ss=ss&qq=11"

@艾默生:应该是这样;PHP的模块似乎具有原始C libcurl所具有的所有功能,而以上内容是相当基本的功能。但是,我不知道要使用的确切功能。如果找不到,请询问堆栈溢出。
grawity
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.