本文介绍了如何使用cURL从文件中读取标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了。

我写了这个变体:

#!/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 我没有收到要发送的标头。

But when I run ./public/curl.sh I am not getting the headers I am sending.

我用env var隔离了该问题:

I isolated the issue with an env var:

$ 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

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

How can I correctly insert a variable in the header section?

推荐答案

让我们问:

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"
}

这篇关于如何使用cURL从文件中读取标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 17:30