Curl to return http status code along with the response

后端 未结 12 1136
我在风中等你
我在风中等你 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:46

    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
    
    0 讨论(0)
  • 2020-12-04 08:50

    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

    0 讨论(0)
  • 2020-12-04 08:53
    while : ; do curl -sL -w "%{http_code} %{url_effective}\\n" http://host -o /dev/null; done
    
    0 讨论(0)
  • 2020-12-04 08:54

    the verbose mode will tell you everything

    curl -v http://localhost
    
    0 讨论(0)
  • 2020-12-04 08:54

    For programmatic usage, I use the following :

    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
    

    It shows following output :

    statuscode : 200
    exitcode : 0
    body : {
      "login": "tj",
      "id": 25254,
      ...
    }
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题