簡體   English   中英

如何在 bash 腳本中使用 HTTPie 捕獲實際的響應代碼和響應正文?

[英]How to capture actual response code and response body with HTTPie in bash script?

我有一個 bash 腳本來使用 HTTPie 調用多個 API。 我想同時捕獲響應正文和 HTTP 狀態代碼。

這是我迄今為止管理的最好的:

rspBody=$( http $URL --check-status --ignore-stdin )
statusCode=$?

命令替換讓我得到正文,“--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"

STDERR 包含一條(通常)3 行消息,其中包含 HTTP 代碼,因此我將其轉儲到臨時文件中,並且仍然能夠在變量中捕獲響應主體(來自 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" }

命令的解釋:

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

https://gist.github.com/jakubroztocil/ad06f159c5afbe278b5fcfa8bf3b5313

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM