Curl to return http status code along with the response

后端 未结 12 1181
我在风中等你
我在风中等你 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:33

    This is a way to retrieve the body "AND" the status code and format it to a proper json or whatever format works for you. Some may argue it's the incorrect use of write format option but this works for me when I need both body and status code in my scripts to check status code and relay back the responses from server.

    curl -X GET -w "%{stderr}{\"status\": \"%{http_code}\", \"body\":\"%{stdout}\"}"  -s -o - “https://github.com” 2>&1
    

    run the code above and you should get back a json in this format:

    {
    "status" : ,
    "body" : 
    }
    

    with the -w write format option, since stderr is printed first, you can format your output with the var http_code and place the body of the response in a value (body) and follow up the enclosing using var stdout. Then redirect your stderr output to stdout and you'll be able to combine both http_code and response body into a neat output

提交回复
热议问题