0

I am trying to get the response of a Http post with curl in Jenkins, I have the following script:

curl -X POST -k -H "Accept: application/json" -H "Content-Type: application/json" --data-binary "@/var/lib/jenkins/workspace/Folder/sessions.json" http://mypage/Data/file.php

As you can see I am sending to file.php a json file, and then I am calling some functions and am returning a specific result.

With that script, I am getting the result I want, but I want to evaluate that result, let's say for example the result was "OK", then I want to assign the result to a variable, and then say if $result=="OK" then do this else do that. How can I do that, I have tried something like this:

if $response == "true" then exit 1 fi

But it does not seem to work out, does anyone know how it can be done?

They marked it as similar to this question PHP cURL, extract an XML response , but I don't see how, because I am not talking about php code, bash code, and I want to store the curl result in a variable....

Thanks in advance!!!

Gaurav Roy
  • 63
  • 1
  • 13
popquinto
  • 33
  • 3
  • 8

1 Answers1

0

You can check the status code if you only need to check if the request was successful :

status=$(curl --write-out '%{http_code}' \
    -s -o /dev/null \
    -H "Accept: application/json" \
    -H "Content-Type: application/json" \
    --data-binary "@/var/lib/jenkins/workspace/Folder/sessions.json" \
    "http://mypage/Data/file.php")

if [ "$status" == "200" ]; then
    echo "request was successful"
else
    echo "error status : $status"
fi

with :

  • --write-out '%{http_code}' : output the status code
  • -o /dev/null : doesn't to output the body
  • -s : doesn't display connection log

As you have specified Accept: application/json, you expect a response in JSON format, so you could use jq JSON parser to parse it :

If the response is :

{ "status": true }

then you can do the following :

status=$(curl -s -H "Accept: application/json" \
    -H "Content-Type: application/json" \
    --data-binary "@/var/lib/jenkins/workspace/Folder/sessions.json" \
    "http://mypage/Data/file.php" | jq -r '.status')

if [ "$status" == "true" ]; then
    echo "request was successful"
else
    echo "error status : $status"
fi

If the response is not in JSON format and the response is OK :

status=$(curl -s -H "Content-Type: application/json" \
    --data-binary "@/var/lib/jenkins/workspace/Folder/sessions.json" \
    "http://mypage/Data/file.php")

if [ "$status" == "OK" ]; then
    echo "request was successful"
else
    echo "error status : $status"
fi
Bertrand Martel
  • 42,756
  • 16
  • 135
  • 159