我使用curl来获取http报头以查找http状态代码并返回响应。我使用命令获取http头信息
curl -I http://localhost
为了得到响应,我使用命令
curl http://localhost
一旦使用了-I标志,我就只得到了头信息,响应就不再存在了。是否有一种方法可以同时获得http响应和头/http状态码在一个命令?
我使用curl来获取http报头以查找http状态代码并返回响应。我使用命令获取http头信息
curl -I http://localhost
为了得到响应,我使用命令
curl http://localhost
一旦使用了-I标志,我就只得到了头信息,响应就不再存在了。是否有一种方法可以同时获得http响应和头/http状态码在一个命令?
当前回答
一行代码,只是为了获得状态代码:
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
其他回答
对于编程使用,我使用以下代码:
curlwithcode() {
code=0
# Run curl in a separate command, capturing output of -w "%{http_code}" into statuscode
# and sending the content to a file with -o >(cat >/tmp/curl_body)
statuscode=$(curl -w "%{http_code}" \
-o >(cat >/tmp/curl_body) \
"$@"
) || code="$?"
body="$(cat /tmp/curl_body)"
echo "statuscode : $statuscode"
echo "exitcode : $code"
echo "body : $body"
}
curlwithcode https://api.github.com/users/tj
显示如下信息:
statuscode : 200
exitcode : 0
body : {
"login": "tj",
"id": 25254,
...
}
根据我的经验,我们通常这样使用旋度
curl -f http://localhost:1234/foo || exit 1
curl: (22) The requested URL returned error: 400 Bad Request
这样我们就可以在curl失败时使用管道,并且它还显示状态代码。
我用过这个:
request_cmd="$(curl -i -o - --silent -X GET --header 'Accept: application/json' --header 'Authorization: _your_auth_code==' 'https://example.com')"
获取HTTP状态
http_status=$(echo "$request_cmd" | grep HTTP | awk '{print $2}')
echo $http_status
为了获得响应体,我使用了这个
output_response=$(echo "$request_cmd" | grep body)
echo $output_response
要获得响应代码和响应:
$ curl -kv https://www.example.org
要得到响应代码:
$ curl -kv https://www.example.org 2>&1 | grep -i 'HTTP/1.1 ' | awk '{print $3}'| sed -e 's/^[ \t]*//'
2>&1:错误存储在输出中,用于解析 Grep:从输出中过滤响应代码行 Awk:从响应代码行中过滤响应代码 Sed:删除前导空白
在末尾追加一行“http_code:200”,然后grep关键字“http_code:”并提取响应代码。
result=$(curl -w "\nhttp_code:%{http_code}" http://localhost)
echo "result: ${result}" #the curl result with "http_code:" at the end
http_code=$(echo "${result}" | grep 'http_code:' | sed 's/http_code://g')
echo "HTTP_CODE: ${http_code}" #the http response code
在这种情况下,您仍然可以使用非静默模式/ verbose模式来获取有关请求的更多信息,例如curl响应体。