Curl to return http status code along with the response

后端 未结 12 1194
我在风中等你
我在风中等你 2020-12-04 08:24

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

12条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 08:55

    I found this question because I wanted BOTH the response and the content in order to add some error handling for the user.

    You can print the HTTP status code to std out and write the contents to another file.

    curl -s -o response.txt -w "%{http_code}" http://example.com
    

    This let's you use logic to decide if the response is worth processing.

    http_response=$(curl -s -o response.txt -w "%{http_code}" http://example.com)
    if [ $http_response != "200" ]; then
        # handle error
    else
        echo "Server returned:"
        cat response.txt    
    fi
    

提交回复
热议问题