如何检查HTTP状态代码并解析有效负载

时间:2018-12-05 16:44:35

标签: bash

假设我在bash脚本中有以下代码:

curl -s https://cat-fact.herokuapp.com/facts/random?animal=cat | jq .

请注意,我希望通过将响应的有效负载传递给jq来显示。

现在假设有时这些卷曲有时会返回404,在这种情况下,我的脚本当前仍然可以成功执行,因此我需要做的是检查返回码和相应的exit 1(例如404或503)。我在Google上四处搜寻,发现https://superuser.com/a/442395/722402暗示--write-out "%{http_code}"可能有用,但是在打印有效载荷之后仅打印http_code即可:

curl -s --write-out "%{http_code}" https://cat-fact.herokuapp.com/facts/random?animal=cat | jq .
  

$ curl -s --write-out“%{http_code}” https://cat-fact.herokuapp.com/facts/random?animal=cat | jq。
  {
    “ _id”:“ 591f98783b90f7150a19c1ab”,
    “ __v”:0,
    “ text”:“猫和小猫应尽可能成对养成,因为猫科的成对互动效果最好。”,
    “ updatedAt”:“ 2018-12-05T05:56:30.384Z”,
    “ createdAt”:“ 2018-01-04T01:10:54.673Z”,
    “已删除”:false,
    “ type”:“ cat”,
    “ source”:“ api”,
    “ used”:false
  }
  200

我真正想要的仍然是输出有效负载,但是仍然能够检查http状态代码并因此失败。我是一个bash菜鸟,所以很难弄清楚这一点。请帮忙吗?

顺便说一下,我使用的是Mac,不确定是否重要(我隐约意识到某些命令在Mac上的工作方式有所不同)


更新,我将其拼凑起来可以进行排序。我认为。不过,它不是很优雅,我正在寻找更好的东西。

func() {
   echo "${@:1:$#-1}";
}
response=$(curl -s --write-out "%{http_code}" https://cat-fact.herokuapp.com/facts/random?animal=cat | jq .) 
http_code=$(echo $response | awk '{print $NF}')
func $response | jq .
if [ $http_code == "503" ]; then
    echo "Exiting with error due to 503"
    exit 1
elif [ $http_code == "404" ]; then
    echo "Exiting with error due to 404"
    exit 1
fi

2 个答案:

答案 0 :(得分:2)

那呢。它使用一个临时文件。看来我有点复杂,但它可以分隔您的内容。

# copy/paste doesn't work with the following
curl -s --write-out \
   "%{http_code}" https://cat-fact.herokuapp.com/facts/random?animal=cat | \ 
   tee test.txt | \      # split output to file and stdout
   sed -e 's-.*\}--' | \ # remove everything before last '}'
   grep 200  && \       # try to find string 200, only in success next step is done
   echo && \            # a new-line to juice-up the output
   cat test.txt | \     # 
   sed 's-}.*$-}-' | \  # removes the last line with status
   jq                   # formmat json

这里有复制/粘贴版本

curl -s --write-out "%{http_code}" https://cat-fact.herokuapp.com/facts/random?animal=cat | tee test.txt | sed -e 's-.*\}--' | grep 200  && echo && cat test.txt | sed 's-}.*$-}-' | jq

答案 1 :(得分:1)

这是我的尝试。希望它也对您有用。

#!/bin/bash

result=$( curl -i -s 'https://cat-fact.herokuapp.com/facts/random?animal=cat'  )


status=$( echo "$result" | grep -E '^HTTPS?/[1-9][.][1-9] [1-9][0-9][0-9]' | grep -o ' [1-9][0-9][0-9] ')
payload=$( echo "$result" | sed -n '/^\s*$/,//{/^\s*$/ !p}' )

echo "STATUS : $status"
echo "PAYLOAD : $payload"

输出

STATUS :  200
PAYLOAD : {"_id":"591f98803b90f7150a19c23f","__v":0,"text":"Cats can't taste sweets.","updatedAt":"2018-12-05T05:56:30.384Z","createdAt":"2018-01-04T01:10:54.673Z","deleted":false,"type":"cat","source":"api","used":false}

AWK版本

payload=$( echo "$result" | awk '{ if( $0 ~ /^\s*$/ ){ c_p = 1 ; next; } if (c_p) { print $0} }' )

致谢!

编辑:通过使用 -i 标志

,我进一步简化了此操作

编辑II:从有效内容中删除了空行

编辑III:包括了 awk 方法,以在 sed 有问题的情况下提取有效载荷