Curl to return http status code along with the response

后端 未结 12 1139
我在风中等你
我在风中等你 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: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,
      ...
    }
    

提交回复
热议问题