在两个单独的变量中同时获取header和curl响应的主体吗? [英] Get both the headers and the body of a curl response in two separated variables?
问题描述
我正在寻找一种进行curl调用并从中获取变量的方法:一种带有标头,另一种带有响应主体。
我已经发现了几个问题,询问如何将标头与正文分开,但人们似乎只对其中之一感兴趣。我需要标头和正文。
我不能使用外部文件来存储正文(因此,不能使用-o $ file)。
我可以使用
headers = $(curl -D / dev / stdout $ URL )
将标头放入一个变量,但是如何将输出重定向到另一个变量? / p>
非常感谢!
head = true
,而IFS =读-r行;如果$ head做
;如果[[-z $ line]],则
;然后
head = false
else
headers + =( $ line)
fi
else
body + =( $ line)
fi
完成< <(curl -sD- $ url | sed's / \r $ //')
printf%s\n $ {headers [@]}
echo ===
printf%s\n $ {body [@]}
将数组的元素连接到单个标量变量中:
the_body = $(IFS = $'\ n'; echo $ body [*]))
在 bash
4.3中,您可以使用命名引用来简化从页眉模式到正文模式的切换:
声明-n section = headers
,而IFS = read -r行;如果[[$ line = $’\r’]],则执行
;然后
声明-n section = body
fi
section + =( $ line)
完成< <(curl -sD- $ url)
由于某些原因,格伦·杰克曼的答案没有抓住回应的主体部分。我必须将curl请求分离到另一个命令扩展中,然后将其用双引号引起来。然后,我不使用数组,而只是将值连接到变量。这对我有用:
output = $(curl -si -d --request POST https:// $ url )
head = true
而读-r行;如果$ head做
;如果[[$ line = $’$ r’]],则为
;然后
head = false
else
header = $ header $'\n' $ line
fi
else
body = $ body $'\n' $ line
fi
完成< <(回显 $ output)
谢谢,格伦!
I am looking for a way to make ONE curl call and get to variables from it: one with the headers and another with the response body.
I've found several questions asking about how to separate headers from body, but people seems only interested in one of them. I need both headers and body.
I cannot use an external file to store the body (thus using -o $file is not an option).
I can use
headers=$(curl -D /dev/stdout $URL)
to get the headers into one variable, but how can I redirect the output to another variable?
Thanks a lot!
head=true
while IFS= read -r line; do
if $head; then
if [[ -z $line ]]; then
head=false
else
headers+=("$line")
fi
else
body+=("$line")
fi
done < <(curl -sD - "$url" | sed 's/\r$//')
printf "%s\n" "${headers[@]}"
echo ===
printf "%s\n" "${body[@]}"
To join the elements of an array into a single scalar variable:
the_body=$( IFS=$'\n'; echo "$body[*]" )
In bash
4.3, you can use named references to simplify switching from "header" mode to "body" mode:
declare -n section=headers
while IFS= read -r line; do
if [[ $line = $'\r' ]]; then
declare -n section=body
fi
section+=("$line")
done < <(curl -sD - "$url")
For some reason, glenn jackman's answer did not catch the body part of the response. I had to separate the curl request into another command expansion and then enclose it in double quotes. Then I did not use arrays, but simply concatenated values to the variables. This works for me:
output=$(curl -si -d "" --request POST https://$url)
head=true
while read -r line; do
if $head; then
if [[ $line = $'\r' ]]; then
head=false
else
header="$header"$'\n'"$line"
fi
else
body="$body"$'\n'"$line"
fi
done < <(echo "$output")
Thank you, Glenn!
这篇关于在两个单独的变量中同时获取header和curl响应的主体吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!