在curl中返回狀態碼和正文

在curl中返回狀態碼和正文

是否可以使用curl呼叫REST服務(POST方法)並取得:

  • HTTP 狀態碼。
  • 響應主體。

其他資訊(如標頭、方法等)與我的用例無關,實際上會增加測試時的混亂。

例如,我正在做:

$ curl -i -H 'Content-Type: application/json' -d @payload.json localhost:8080/apply
HTTP/1.1 100 

HTTP/1.1 400 
Content-Type: text/plain;charset=UTF-8
Content-Length: 42
Date: Fri, 22 Oct 2021 16:29:18 GMT
Connection: close

Invalid product: product does not exist

我知道服務正在返回400我可以看到的內容,而且我也可以看到回應錯誤Invalid product: product does not exist,所以這很好。

但是,是否可以去掉顯示器的其餘部分?

答案1

您可以將/與包含變數的格式字串一起使用,而不是-i顯示回應標頭:-w--write-outhttp_code

curl --write-out '%{http_code}\n' ...

將在正文後列印回應狀態(和換行符)。檢查man curl您可能會發現有用的其他變數。

答案2

基於 @DonHolgo 的解決方案,人們可以在寫入中添加更多信息,如下所示:

curl --location 'https://foo.acme.com' \
--request POST \
--write-out '\nhttp_code=%{http_code}\nexitcode=%{exitcode}\n' --silent --show-error \
--header 'Content-Type: application/json' \
--data '{"foo": "bar","baz":"bim"}'

本例中的輸出與 POST 的響應結合:

{"requestId":"550aa1ff-0001-bf46-79ae-018cfe00dff7"}
http_code=202
exitcode=0

您可以在變數中擷取該資訊並處理 3 件事:POST 回應 (JSON)、HTTP 回應碼以及 cURL 指令的退出程式碼。

相關內容