Curl to return http status code along with the res

2020-02-02 04:09发布

I use curl to get http headers to find http status code and also return response. I get the http headers with the command

curl -I http://localhost

To get the response, I use the command

curl http://localhost

As soon as use the -I flag, I get only the headers and the response is no longer there. Is there a way to get both the http response and the headers/http status code in in one command?

标签: shell curl
9条回答
一纸荒年 Trace。
2楼-- · 2020-02-02 05:07

I use this command to print the status code without any other output. Additionally, it will only perform a HEAD request and follow the redirection (respectively -I and -L).

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

This makes it very easy to check the status code in a health script:

sh -c '[ $(curl -o -I -L -s -w "%{http_code}" http://localhost) -eq 200 ]'
查看更多
小情绪 Triste *
3楼-- · 2020-02-02 05:10

The -i option is the one that you want:

curl -i http://localhost

-i, --include Include protocol headers in the output (H/F)

Alternatively you can use the verbose option:

curl -v http://localhost

-v, --verbose Make the operation more talkative

查看更多
趁早两清
4楼-- · 2020-02-02 05:11

I have used this :

    request_cmd="$(curl -i -o - --silent -X GET --header 'Accept: application/json' --header 'Authorization: _your_auth_code==' 'https://example.com')"

To get the HTTP status

    http_status=$(echo "$request_cmd" | grep HTTP |  awk '{print $2}')
    echo $http_status

To get the response body I've used this

    output_response=$(echo "$request_cmd" | grep body)
    echo $output_response
查看更多
登录 后发表回答