【问题标题】:Is there a way to pass the content of a file to curl?有没有办法将文件的内容传递给 curl?
【发布时间】:2015-06-25 21:48:20
【问题描述】:

我想从命令行执行一个具有多部分/混合边界的相当复杂的 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

有什么简单直接的方法吗?我知道有些客户端库有其惯用的处理方式,但我很想知道是否有办法从命令行执行此操作。

【问题讨论】:

    标签: http curl


    【解决方案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
    
    ...
    

    【讨论】:

    猜你喜欢
    • 2020-09-20
    • 1970-01-01
    • 2019-05-09
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    相关资源
    最近更新 更多