curl:从文件读取标题

dohp0rv5  于 2022-11-13  发布在  其他
关注(0)|答案(5)|浏览(141)

在--dump-header写了一个文件之后,如何将这些头读回到下一个请求中呢?我想从一个文件中读取它们,因为它们有很多。
我试过标准在:cat headers | curl -v -H - ...
我实际上是使用Firebug中的特性来“复制请求头”,然后将其保存到一个文件中。

sxpgvts3

sxpgvts31#

自 curl 7.55.0以来

简单:

$ curl -H @header_file https://example.com

...其中头文件是一个纯文本文件,每行都有一个HTTP头。如下所示:

Color: red
Shoesize: 11
Secret: yes
User-Agent: foobar/3000
Name: "Joe Smith"

curl 前7.55.0

curl没有办法从文件中批量修改这样的头文件。它们必须用-H逐个修改。
对于旧的curl版本,最好的方法可能是编写一个shell脚本,从文件中收集所有的头文件并使用它们,例如:

#!/bin/sh
while read line; do
  args="$args -H '$line'";
done
curl $args https://example.com

按如下方式调用脚本:

$ sh script.sh < header_file
bwntbbo3

bwntbbo32#

不如这样:

curl -v -H "$(cat headers.txt)" yourhost.com

其中headers.txt看起来像

Header1: bla
Header2: blupp

在BASH工作。

w1jd8yoj

w1jd8yoj3#

从curl 7.55.0开始,它现在可以从文件中读取头:

curl -H @filename

现在就这么简单。

zyfwsgd6

zyfwsgd64#

正如@dmitry-sutyagin所回答的,如果你的curl版本至少是7.55.0,你可以使用@符号从文件中读取头文件:

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

如果你的curl不是7.55.0或更新版本,这里有一个有用的技巧:

  • 使用选项-K/--config <config file>,并在文本文件中放置几行-H/--header <header>

例如:

  1. curl --dump-header foo.txt https://www.google.com/
    1.如有必要,dos2unix foo.txt
    1.手动或使用脚本将文件转换为-H 'header'行:
cat foo.txt |
  awk '$1 == "Set-Cookie:"' |
  perl -ne "chomp; next if /^\\s*\$/; if (/'/) { warn; next } print \"-H '\$_'\\n\";" |
  tee headerfile.txt

这可能会输出如下所示的内容:

-H 'Set-Cookie: 1P_JAR=2018-02-13-08; [...]'
-H 'Set-Cookie: NID=123=n7vY1W8IDElvf [...]'
  1. curl --config headerfile.txt https://www.google.com/
1cklez4t

1cklez4t5#

curl $(xargs -a headers.txt printf "-H '%s'") example.org

相关问题