简体   繁体   English

从 Curl 请求中获取状态码和响应体

[英]Obtain Status Code and Response Body from Curl Request

I want to check http repsonse codes from curl yet still be able to retrieve the returned data and store it in a variable.我想从curl检查 http 响应代码,但仍然能够检索返回的数据并将其存储在变量中。

I found this answer very helpful: https://superuser.com/a/862395/148175 The user describes how he created a new filedescriptor 3 that redirects to STDOUT .我发现这个答案非常有帮助: https ://superuser.com/a/862395/148175 用户描述了他如何创建一个重定向到STDOUT的新文件描述符3

Then he ran curl in a subshell where he captured the output of -w "%{http_code}" into a variable HTTP_STATUS and the output to the STDOUT with -o >(cat >&3) .然后他在子 shell 中运行curl在那里他将-w "%{http_code}" HTTP_STATUS -w "%{http_code}"的输出捕获到变量HTTP_STATUS并使用-o >(cat >&3)输出到 STDOUT。

My problem is that I want to capture the output of the STDOUT into a variable after I run curl within a function.我的问题是我想在函数中运行 curl 后将 STDOUT 的输出捕获到一个变量中。

This is my script:这是我的脚本:

#!/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

What it does:它能做什么:

The output of curl is directed to STDOUT and printed in the console window. curl 的输出被定向到STDOUT并打印在控制台窗口中。

What's desired想要什么

Since the function calling curl is run in a subshell, it should direct the output to the variable responsedata .由于调用curl的函数在子 shell 中运行,因此它应该将输出定向到变量responsedata

From what I understand, you want this function to output Error: HTTP repsonse is $status if $status is not equal to 200 and otherwise output the response body, so here is the code for that.据我了解,您希望此函数输出Error: HTTP repsonse is $status如果$status不等于200 ,否则输出响应正文,所以这里是代码。 I did not see a need for an additional file descriptor, so I removed it.我认为不需要额外的文件描述符,所以我删除了它。

#!/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

Edit: Simplified the evaluation of the status code from the curl response to just get the last three characters aka the status code.编辑:简化了 curl 响应中状态代码的评估,只需获取最后三个字符,即状态代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM