我使用curl来获取http报头以查找http状态代码并返回响应。我使用命令获取http头信息

curl -I http://localhost

为了得到响应,我使用命令

curl http://localhost

一旦使用了-I标志,我就只得到了头信息,响应就不再存在了。是否有一种方法可以同时获得http响应和头/http状态码在一个命令?


当前回答

我使用以下方法在控制台中获得返回代码和响应体。

注:使用tee将输出附加到一个文件以及控制台,这解决了我的目的。

示例CURL调用供参考:

curl -s -i -k --location --request POST ''${HOST}':${PORT}/api/14/project/'${PROJECT_NAME}'/jobs/import' \
--header 'Content-Type: application/yaml' \
--header 'X-Rundeck-Auth-Token: '${JOB_IMPORT_TOKEN}'' \
--data "$(cat $yaml_file)" &>/dev/stdout | tee -a $response_file

return_code=$(cat $response_file | head -3 | tail -1 | awk {'print $2'})

if [ "$return_code" != "200" ]; then
  echo -e "\Job import api call failed with rc: $return_code, please rerun or change pipeline script."
  exit $return_code
else
  echo "Job import api call completed successfully with rc: $return_code"
fi

希望这能帮助到一些人。

其他回答

我使用这个命令打印状态代码,而不输出任何其他结果。此外,它将只执行HEAD请求并遵循重定向(分别为-I和-L)。

curl -o -I -L -s -w "%{http_code}" http://localhost

这使得检查运行状况脚本中的状态代码非常容易:

sh -c '[ $(curl -o -I -L -s -w "%{http_code}" http://localhost) -eq 200 ]'

我可以通过查看curl文档来得到一个解决方案,该文档指定使用-来将输出输出到stdout。

curl -o - -I http://localhost

要用http返回代码获得响应,我可以这样做

curl -o /dev/null -s -w "%{http_code}\n" http://localhost

一行代码,只是为了获得状态代码:

curl -s -i https://www.google.com | head -1

将其更改为head -2也会给出时间。


如果你想要一个while-true循环,它会是:

URL="https://www.google.com"

while true; do
    echo "------"
    curl -s -i $URL | head -2
    sleep 2;
done

直到您执行cmd+C(或Windows中的ctrl+C)。

------
HTTP/2 200
date: Sun, 07 Feb 2021 20:03:38 GMT
------
HTTP/2 200
date: Sun, 07 Feb 2021 20:03:41 GMT
------
HTTP/2 200
date: Sun, 07 Feb 2021 20:03:43 GMT
------
HTTP/2 200
date: Sun, 07 Feb 2021 20:03:45 GMT
------
HTTP/2 200
date: Sun, 07 Feb 2021 20:03:47 GMT
------
HTTP/2 200
date: Sun, 07 Feb 2021 20:03:49 GMT

这对我来说很管用:

curl -Uri 'google.com' | select-object StatusCode

一个清晰的使用管道读取

function cg(){
    curl -I --silent www.google.com | head -n 1 | awk -F' ' '{print $2}'
}
cg
# 200

欢迎在这里使用我的dotfile脚本

解释

——silent:使用管道时不显示进度条 head -n 1:只显示第一行 -F' ':使用分隔符分隔文本 '{print $2}':显示第二列