我想从命令行执行一个包含多部分/混合边界的相当复杂的HTTP请求。
POST /batch HTTP/1.1
Host: www.googleapis.com
Content-length: 592
Content-type: multipart/mixed; boundary=batch_0123456789
Authorization: Bearer authorization_token
--batch_0123456789
Content-Type: application/http
Content-ID: <item1:user@example.com>
Content-Transfer-Encoding: binary
POST /drive/v2/files/fileId/permissions
Content-Type: application/json
Content-Length: 71
{
"role": "reader",
"type": "user",
"value": "user@example.com"
}
--batch_0123456789
Content-Type: application/http
Content-ID: <item2:user@example.com>
Content-Transfer-Encoding: binary
POST /drive/v2/files/fileId/permissions
Content-Type: application/json
Content-Length: 71
{
"role": "reader",
"type": "user",
"value": "user@example.com"
}
--batch_0123456789--
理想情况下,我想将此请求放入文件中,然后只需调用curl来执行该HTTP请求。
curl myrequest.txt
有没有简单明了的方法呢?我知道有些客户端库有其惯用的处理方式,但我很想知道是否有办法从命令行执行此操作。
答案 0 :(得分:1)
您可以使用--config
选项(有关详细信息,请参阅manual的“配置文件”部分):
curl --config myrequest.txt
我认为在配置文件中嵌入多行POST主体并不是一种干净的方法。您可以使用\r\n
替换每个换行符(多部分请求需要CRLF换行符):
url = "http://www.googleapis.com/batch"
header = "Content-length: 592"
header = "Content-type: multipart/mixed; boundary=batch_0123456789"
header = "Authorization: Bearer authorization_token"
data-binary = "--batch_0123456789\r\nContent-Type: application/http\r\nContent-ID: <item1:user@example.com>\r\nContent-Transfer-Encoding: binary\r\n\r\n..."
但这并不容易阅读。
或者,您可以将POST正文放在单独的文件中。例如:
<强> myrequest.txt 强>
url = "http://www.googleapis.com/batch"
header = "Content-length: 592"
header = "Content-type: multipart/mixed; boundary=batch_0123456789"
header = "Authorization: Bearer authorization_token"
data-binary = "@myrequestbody.txt"
<强> myrequestbody.txt 强>
--batch_0123456789
Content-Type: application/http
Content-ID: <item1:user@example.com>
Content-Transfer-Encoding: binary
POST /drive/v2/files/fileId/permissions
Content-Type: application/json
Content-Length: 71
...