我发现了很多关于如何在 cURL 中使用简单 POST 命令的示例,但没有找到关于如何发送完整 HTTP POST 命令的示例,其中包含:
- 标头(基本身份验证)
- HTTP 参数 (
s=1&r=33
) - 主体数据,一些 XML 字符串
我发现的是:
echo "this is body" | curl -d "ss=ss&qq=11" http://localhost/
这不起作用,它将 HTTP 参数作为正文发送。
答案1
如果需要将查询字符串参数(有时称为“GET 参数”或“URL 参数”)与 POST 数据混合,则可以使用 /-G
和--get
开关--no-get
。
引用手册页:
-G, --get
When used, this option makes all data specified with -d, --data,
--data-binary or --data-urlencode to be used in an HTTP GET
request instead of the POST request that otherwise would be used.
The data is appended to the URL with a '?' separator.
If used in combination with -I, --head, the POST data is instead
appended to the URL with a HEAD request.
Providing -G, --get multiple times has no extra effect. Disable
it again with --no-get.
因此,如果您想curl
对查询字符串参数进行编码,并指定 POST 数据,则可以使用例如来进行-d "this is body" --get --data-urlencode "ss=ss" --data-urlencode "qq=11"
。
答案2
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 "[email protected]" # the specified file is sent as an attachment
-d "foo=bar"
-d "foo=<foovalue.txt"
-d "[email protected]"
-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"
答案3
声誉不足以发表评论,因此请保留此答案,希望它有所帮助。
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}"