Curl to return http status code along with the response

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

    My way to achieve this:

    To get both (header and body), I usually perform a curl -D- as in:

    $ curl -D- http://localhost:1234/foo
    HTTP/1.1 200 OK
    Connection: Keep-Alive
    Transfer-Encoding: chunked
    Content-Type: application/json
    Date: Wed, 29 Jul 2020 20:59:21 GMT
    
    {"data":["out.csv"]}
    

    This will dump headers (-D) to stdout (-) (Look for --dump-header in man curl).

    IMHO also very handy in this context:

    I often use jq to get that json data (eg from some rest APIs) formatted. But as jq doesn't expect a HTTP header, the trick is to print headers to stderr using -D/dev/stderr. Note that this time we also use -sS (--silent, --show-errors) to suppress the progress meter (because we write to a pipe).

    $ curl -sSD/dev/stderr http://localhost:1231/foo | jq .
    HTTP/1.1 200 OK
    Connection: Keep-Alive
    Transfer-Encoding: chunked
    Content-Type: application/json
    Date: Wed, 29 Jul 2020 21:08:22 GMT
    
    {
      "data": [
        "out.csv"
      ]
    }
    

    I guess this also can be handy if you'd like to print headers (for quick inspection) to console but redirect body to a file (eg when its some kind of binary to not mess up your terminal):

    $ curl -sSD/dev/stderr http://localhost:1231 > /dev/null
    HTTP/1.1 200 OK
    Connection: Keep-Alive
    Transfer-Encoding: chunked
    Content-Type: application/json
    Date: Wed, 29 Jul 2020 21:20:02 GMT
    
    

    Be aware: This is NOT the same as curl -I ! As -I will perform a HEAD request and not a GET request (Look for --head in man curl. Yes: For most HTTP servers this will yield same result. But I know a lot of business applications which don't implement HEAD request at all ;-P

提交回复
热议问题