【问题标题】:How to read headers from file using cURL?如何使用 cURL 从文件中读取标题?
【发布时间】:2014-07-02 21:32:10
【问题描述】:

我找到了this

我写了这个变种:

#!/bin/bash
while read line ; do
  headers="$headers -H '$line'"
done < public/headers.txt
echo $headers
curl -X PUT \
     $headers \
     -d @'public/example.json' \
     echo.httpkit.com

headers.txt 我有:

X-PAYPAL-SECURITY-USERID:123
X-PAYPAL-SECURITY-PASSWORD:123

但是当我运行 ./public/curl.sh 时,我没有收到要发送的标头。

我用一个环境变量隔离了这个问题:

$ x='-H some:asd'
$ curl $x echo.httpkit.com
=> header was NOT present
$ curl -H 'some:asd' echo.httpkit.com
=> header was present
$ curl -H some:asd echo.httpkit.com
=> header was present

如何在标题部分正确插入变量?

【问题讨论】:

  • 你怎么知道标题是否存在?我正在检查curl -v $x echo.httpkit.com 2&gt;&amp;1 &gt;/dev/null | grep some:,它匹配,看起来标题就在那里。你的“curl --version”是什么?

标签: linux shell curl


【解决方案1】:

我们问shellcheck

In yourscript line 3:
  headers="$headers -H '$line'"
                       ^-- SC2089: Quotes/backslashes will be treated literally. 
                                   Use an array.

好的,那我们就这样做吧:

#!/bin/bash
while read line ; do
headers=("${headers[@]}" -H "$line")
done < public/headers.txt
echo "${headers[@]}"
curl -X PUT \
   "${headers[@]}" \
   -d @'public/example.json' \
   echo.httpkit.com

结果:

{
  "method": "PUT",
  "uri": "/",
  "path": {
    "name": "/",
    "query": "",
    "params": {}
  },
  "headers": {
    "host": "echo.httpkit.com",
    "user-agent": "curl/7.35.0",
    "accept": "*/*",
    "x-paypal-security-userid": "123",      //      <----- Yay!!
    "x-paypal-security-password": "123",
    "content-length": "32",
    "content-type": "application/x-www-form-urlencoded"
  },
  "body": "\"This is text from example.json\"",
  "ip": "127.0.0.1",
  "powered-by": "http://httpkit.com",
  "docs": "http://httpkit.com/echo"
}

【讨论】:

    【解决方案2】:

    如果您不想将 HTTP 标头放在命令行上(可能出于安全原因),您仍然可以让 curl 直接从文件中读取它们。

    curl -H @headerfile.txt https://www.google.com/  # requires curl >=7.55.0
    

    如果您的 curl 版本早于 7.55.0:

    • 使用选项-K/--config &lt;config file&gt;,并在文本文件中添加几行-H/--header &lt;header&gt;

    更多详情请看我在原文章中的回答:

    https://stackoverflow.com/a/48762561/5201675

    【讨论】:

      猜你喜欢
      • 2011-07-02
      • 1970-01-01
      • 2021-06-20
      • 1970-01-01
      • 1970-01-01
      • 2012-06-20
      • 2011-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多