我有一个bash脚本,可以使用HTTPie调用多个API。我想捕获响应主体和HTTP状态代码。
这是我到目前为止所能做到的最好的:
rspBody=$( http $URL --check-status --ignore-stdin )
statusCode=$?
Run Code Online (Sandbox Code Playgroud)
命令替换使我可以获取主体,而“ --check-status”标志为我提供了与代码族相对应的简化代码(例如0、3、4等)。
问题是我需要区分是401代码还是404代码,但我只能得到4。
有没有一种方法可以获取实际的状态代码,而不必进行冗长的转储到文件中并解析内容?
[编辑]
这是我的解决方法,以防他人受骗,但如果您有一个建议,我仍然希望有一个更好的主意:
TMP=$(mktemp)
FLUSH_RSP=$( http POST ${CACHE_URL} --check-status --ignore-stdin 2> "$TMP")
STAT_FAMILY=$?
flush_err=$(cat "$TMP" | awk '{
where = match($0, /[0-9]+/)
if (where) {
print substr($0, RSTART, RLENGTH);
}
}' -)
rm "$TMP"
Run Code Online (Sandbox Code Playgroud)
STDERR包含一个(通常)带有HTTP代码的3行消息,因此我将其转储到临时文件中,仍然能够捕获变量中的响应正文(来自STDOUT)。
然后,我解析该临时文件以查找数字,但这对我来说似乎很脆弱。
尚无现成的解决方案,但只需编写一些脚本即可实现。例如:
STATUS=$(http -hdo ./body httpbin.org/get 2>&1 | grep HTTP/ | cut -d ' ' -f 2)
BODY=$(cat ./body)
rm ./body
echo $STATUS
# 200
echo $BODY
# { "args": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "identity", "Host": "httpbin.org", "User-Agent": "HTTPie/1.0.0-dev" }, "origin": "84.242.118.58", "url": "http://httpbin.org/get" }
Run Code Online (Sandbox Code Playgroud)
命令说明:
http --headers \ # Print out the response headers (they would otherwise be supressed for piped ouput)
--download \ # Enable download mode
--output=./body \ # Save response body to this file
httpbin.org/get 2>&1 \ # Merge STDERR into STDOUT (with --download, console output otherwise goes to STDERR)
| grep HTTP/ \ # Find the Status-Line
| cut -d ' ' -f 2 # Get the status code
Run Code Online (Sandbox Code Playgroud)
https://gist.github.com/jakubroztocil/ad06f159c5afbe278b5fcfa8bf3b5313