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

use*_*020 46 curl

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

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

我发现的是:

echo "this is body" | curl -d "ss=ss&qq=11" http://localhost/
Run Code Online (Sandbox Code Playgroud)

这不起作用,它将 HTTP 参数作为正文发送。

use*_*686 61

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

"http://localhost/?name=value&othername=othervalue"
Run Code Online (Sandbox Code Playgroud)

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

-u "user:password"
Run Code Online (Sandbox Code Playgroud)

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"
Run Code Online (Sandbox Code Playgroud)

所以,总结一下:

curl -d "this is body" -u "user:pass" "http://localhost/?ss=ss&qq=11"
Run Code Online (Sandbox Code Playgroud)


Tii*_*ina 21

没有足够的声誉来发表评论,所以将此作为答案希望它有所帮助。

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}
Run Code Online (Sandbox Code Playgroud)

这是我用于 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
Run Code Online (Sandbox Code Playgroud)

如果 url 参数包含诸如“+”之类的特殊符号,则对它们的每个参数(包含特殊符号)使用 --data-urlencode:

curl -G -H "Accept:..." -H "..." --data-urlencode "beginTime=${time}+${zone}" --data-urlencode "endTime=${time}+${zone}" "${url}"
Run Code Online (Sandbox Code Playgroud)