Created
November 24, 2015 17:52
-
-
Save maxcnunes/9f77afdc32df354883df to your computer and use it in GitHub Desktop.
Curl - Get status code and response body
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
URL="http://stackoverflow.com/" | |
# store the whole response with the status at the and | |
HTTP_RESPONSE=$(curl --silent --write-out "HTTPSTATUS:%{http_code}" -X POST $URL) | |
# extract the body | |
HTTP_BODY=$(echo $HTTP_RESPONSE | sed -e 's/HTTPSTATUS\:.*//g') | |
# extract the status | |
HTTP_STATUS=$(echo $HTTP_RESPONSE | tr -d '\n' | sed -e 's/.*HTTPSTATUS://') | |
# print the body | |
echo "$HTTP_BODY" | |
# example using the status | |
if [ ! $HTTP_STATUS -eq 200 ]; then | |
echo "Error [HTTP status: $HTTP_STATUS]" | |
exit 1 | |
fi |
one should use quotes in the echo in order to avoid loose of linebreaks
HTTP_BODY=$(echo` "$HTTP_RESPONSE" | sed -e 's/HTTPSTATUS:.*//g')
There is a syntax error in this. unmatched ending for the accent `
I've been able to get the http status by doing the following:
URL="http://stackoverflow.com/"
echo STATUS=$(curl -ILSso /dev/null -w '%{response_code}' $URL | head -n 1 | cut -d$' ' -f2)
Here is what I came up with:
curl -sL -w ' { "statusCode": %{http_code}} ' -X POST "${headers[@]}" "${endpoint}" \
-d "${body}" "$curl_opts" | jq -ren '[inputs] | add'
the curl command produces:
{"message":"Change event processed","status":"success"}
I just add another object with the status code
{ "statusCode": 202}
and have jq smush them together:
jq -ren '[inputs] | add'
So, if you use jq
and slurp, you would get:
[
{
"message": "Change event processed",
"status": "success"
},
{
"statusCode": 202
}
]
Instead, we squeeze them together and get:
jq -n '[inputs] | add'
{
"message": "Change event processed",
"status": "success",
"statusCode": 202
}
we can then save and dump this and then use jq
to return status code:
jq -re '.statusCode >= 200 and .statusCode < 300' > /dev/null
Remember: in bash the status code of the last command is the status code of the function
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, here we have been able to get the "HTTP status code" and the "response body". Is it also possible to get the "HTTP Header values" using $HTTP_RESPONSE?