如何检查 curl 是否成功并打印消息?

Adi*_*han 6 unix bash shell terminal curl

我正在尝试使用 IF Else 条件执行 CURL。呼叫成功时打印一条成功的消息,否则打印呼叫失败。

我的示例卷曲看起来像:

curl 'https://xxxx:1234xxxx@abc.dfghj.com/xl_template.get_web_query?id=1035066' > HTML_Output.html
Run Code Online (Sandbox Code Playgroud)

我想使用 Shell 做同样的事情。

使用 JavaScript:

if(res.status === 200){console.log("Yes!! The request was successful")}
else {console.log("CURL Failed")}
Run Code Online (Sandbox Code Playgroud)

另外,我看到了 CURL 百分比,但我不知道如何检查 CURL 的百分比。请帮忙。

卷曲输出 卷曲输出

Bal*_*ddy 6

实现这一目标的一种方法,例如,

HTTPS_URL="https://xxxx:1234xxxx@abc.dfghj.com/xl_template.get_web_query?id=1035066"
CURL_CMD="curl -w httpcode=%{http_code}"

# -m, --max-time <seconds> FOR curl operation
CURL_MAX_CONNECTION_TIMEOUT="-m 100"

# perform curl operation
CURL_RETURN_CODE=0
CURL_OUTPUT=`${CURL_CMD} ${CURL_MAX_CONNECTION_TIMEOUT} ${HTTPS_URL} 2> /dev/null` || CURL_RETURN_CODE=$?
if [ ${CURL_RETURN_CODE} -ne 0 ]; then  
    echo "Curl connection failed with return code - ${CURL_RETURN_CODE}"
else
    echo "Curl connection success"
    # Check http code for curl operation/response in  CURL_OUTPUT
    httpCode=$(echo "${CURL_OUTPUT}" | sed -e 's/.*\httpcode=//')
    if [ ${httpCode} -ne 200 ]; then
        echo "Curl operation/command failed due to server return code - ${httpCode}"
    fi
fi
Run Code Online (Sandbox Code Playgroud)


hee*_*ayl 5

您可以使用curl的-w( --write-out) 选项打印 HTTP 代码:

curl -s -w '%{http_code}\n' 'https://xxxx:1234xxxx@abc.dfghj.com/xl_template.get_web_query?id=1035066'
Run Code Online (Sandbox Code Playgroud)

它将显示站点返回的 HTTP 代码。

curl为各种场景提供了一大堆退出代码,请检查man curl.


Bar*_*mar 5

与大多数程序一样,curl如果出现错误,则返回非零退出状态,因此您可以使用 来测试它if

if curl 'https://xxxx:1234xxxx@abc.dfghj.com/xl_template.get_web_query?id=1035066' > HTML_Output
then echo "Request was successful"
else echo "CURL Failed"
fi
Run Code Online (Sandbox Code Playgroud)

如果下载在中间失败,我不知道有什么方法可以找出百分比。

  • 对于非 200 代码,它也会返回成功。请参阅https://superuser.com/questions/272265/getting-curl-to-output-http-status-code (6认同)