[英]Obtain Status Code and Response Body from Curl Request
我想從curl
檢查 http 響應代碼,但仍然能夠檢索返回的數據並將其存儲在變量中。
我發現這個答案非常有幫助: https ://superuser.com/a/862395/148175 用戶描述了他如何創建一個重定向到STDOUT
的新文件描述符3
。
然后他在子 shell 中運行curl
在那里他將-w "%{http_code}"
HTTP_STATUS
-w "%{http_code}"
的輸出捕獲到變量HTTP_STATUS
並使用-o >(cat >&3)
輸出到 STDOUT。
我的問題是我想在函數中運行 curl 后將 STDOUT 的輸出捕獲到一個變量中。
這是我的腳本:
#!/bin/bash
exec 3>&1
function curlBinData {
HTTP_STATUS=$(curl -s -w "%{http_code}" -o >(cat >&3) https://www.google.com --data-binary $1)
if [ $HTTP_STATUS -ne 200 ]; then
echo Error: HTTP repsonse is $HTTP_STATUS
exit
fi
}
responsedata=$(curlBinData '{"head":5}')
echo $responsedata
它能做什么:
curl 的輸出被定向到STDOUT
並打印在控制台窗口中。
想要什么
由於調用curl
的函數在子 shell 中運行,因此它應該將輸出定向到變量responsedata
。
據我了解,您希望此函數輸出Error: HTTP repsonse is $status
如果$status
不等於200
,否則輸出響應正文,所以這里是代碼。 我認為不需要額外的文件描述符,所以我刪除了它。
#!/bin/bash
function curlBinData {
local res=$(curl -s -w "%{http_code}" https://www.google.com --data-binary $1)
local body=${res::-3}
local status=$(printf "%s" "$res" | tail -c 3)
if [ "$status" -ne "200" ]; then
echo "Error: HTTP repsonse is $status"
exit
fi
echo $body
}
responsedata=$(curlBinData '{"head":5}')
echo $responsedata
編輯:簡化了 curl 響應中狀態代碼的評估,只需獲取最后三個字符,即狀態代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.