Perl/ curl How to get Status Code and Response Body

curl, linux, perl

Solution

...Will give me the entire header plus the response.

...in a neat format that allows me to separate them into two separate variables.

Since header and body are simply delimited by an empty line you can split the content on this line:

 my ($head,$body) = split( m{\r?\n\r?\n}, `curl -si http://example.com `,2 );

And to get the status code from the header

 my ($code) = $head =~m{\A\S+ (\d+)};

You might also combine this into a single expression with a regexp, although this might be harder to understand:

my ($code,$body) = `curl -si http://example.com` 
      =~m{\A\S+ (\d+) .*?\r?\n\r?\n(.*)}s;

Problem

I am trying to write a simple perl script that calls and API and if the status code is 2xx the do something with the response. While if it is 4xx or 5xx then do something else. The issue I am encountering is I am able to either get the response code (using a custom write-out formatter and pass the output somewhere else) or I can get the whole response and the headers. ``` my $curlResponseCode = `curl -s -o /dev/null -w "%{http_code}" ....`; ``` Will give me the status code only. ``` my $curlResponse = `curl -si ...`; ``` Will give me the entire header plus the response. My question is how can I obtain the response body from the server and the http status code in a neat format that allows me to separate them into two separate variables. Unfortunately I cannot use LWP or any other separate libraries. Thanks in advance. -Spencer

Original source