Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl/ curl How to get Status Code and Response Body

Tags:

linux

curl

perl

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

like image 691
recneps Avatar asked Feb 26 '15 20:02

recneps


People also ask

How do I get my curl response code?

Remember that you can use curl's --write-out option to extract the response code. See the --write-out section. To make curl return an error for response codes >= 400, you need to use --fail or --fail-with-body . Then curl will exit with error code 22 for such occurrences.

How can I make my body curl?

To post data in the body of a request message using Curl, you need to pass the data to Curl using the -d or --data command line switch. The Content-Type header indicates the data type in the body of the request message.

What is curl in Perl?

WWW::Curl is a Perl extension interface for libcurl.


2 Answers

I came up with this solution:

URL="http://google.com"

# store the whole response with the status at the and
HTTP_RESPONSE=$(curl --silent --write-out "HTTPSTATUS:%{http_code}" -X POST $URL)

# extract the body
HTTP_BODY=$(echo $HTTP_RESPONSE | sed -e 's/HTTPSTATUS\:.*//g')

# extract the status
HTTP_STATUS=$(echo $HTTP_RESPONSE | tr -d '\n' | sed -e 's/.*HTTPSTATUS://')

# print the body
echo "$HTTP_BODY"

# example using the status
if [ ! $HTTP_STATUS -eq 200  ]; then
  echo "Error [HTTP status: $HTTP_STATUS]"
  exit 1
fi
like image 89
maxcnunes Avatar answered Sep 28 '22 04:09

maxcnunes


...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;
like image 20
Steffen Ullrich Avatar answered Sep 28 '22 05:09

Steffen Ullrich