我试图在Jenkins中获得带有curl的Http帖子的响应,我有以下脚本:
this
http://mypage/Data/file.php
正如您所看到我发送 file.php json文件,然后我正在调用某些函数并返回特定结果。
使用该脚本,我得到了我想要的结果,但我想评估结果,比方说结果是“OK”,然后我想将结果分配给变量,然后说 if $ result ==“OK”然后执行此操作 else 执行此操作。我怎么能这样做,我尝试过这样的事情:
curl -X POST -k -H "Accept: application/json" -H "Content-Type: application/json" --data-binary "@/var/lib/jenkins/workspace/Folder/sessions.json"
但它似乎没有成功,是否有人知道如何做到这一点?
他们将其标记为与此问题类似 PHP cURL, extract an XML response ,但我不知道如何,因为我不是在谈论PHP代码,bash代码,我想将curl结果存储在变量中....
提前致谢!!!
答案 0 :(得分:0)
如果您只需要检查请求是否成功,您可以查看状态代码:
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}'
:输出状态代码-o /dev/null
:不输出正文-s
:不显示连接日志正如您指定Accept: application/json
,您希望以JSON格式进行响应,因此您可以使用jq
JSON解析器来解析它:
如果回复是:
{ "status": true }
然后您可以执行以下操作:
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
如果响应不是JSON格式且响应为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