Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get both the headers and the body of a curl response in two separated variables?

Tags:

bash

curl

I am looking for a way to make ONE curl call and get to variables from it: one with the headers and another with the response body.

I've found several questions asking about how to separate headers from body, but people seems only interested in one of them. I need both headers and body.

I cannot use an external file to store the body (thus using -o $file is not an option).

I can use

headers=$(curl -D /dev/stdout $URL)

to get the headers into one variable, but how can I redirect the output to another variable?

Thanks a lot!

like image 262
Daniel Avatar asked Sep 15 '14 16:09

Daniel


People also ask

How do you get the curl response header?

In default mode, curl doesn't display request or response headers, only displaying the HTML contents. To display both request and response headers, we can use the verbose mode curl -v or curl -verbose . In the resulting output: The lines beginning with > indicate request headers.

How do I print a curl response?

By default, curl doesn't print the response headers. It only prints the response body. To print the response headers, too, use the -i command line argument.

How do I view response headers in PHP?

Response Headers in cURL There is a simple solution built into cURL if you are only interested in the response headers and not the content of the body. By setting the CURLOPT_HEADER and CURLOPT_NOBODY options to true, the result of curl_exec() will only contain the headers.


1 Answers

I would like to share a way to parse curl response without any external program, bash only.

First, get the response of a curl request passing -sw "%{http_code}".

res=$(curl -sw "%{http_code}" $url)

The result will be a string containing the body followed by the http code.

Then, get the http code:

http_code="${res:${#res}-3}"

And the body:

if [ ${#res} -eq 3 ]; then
  body=""
else
  body="${res:0:${#res}-3}"
fi

Note that if the length of http_code and response are equal (length 3), body is empty. Else, just strip out the http code and you get the body.

like image 154
0x10203040 Avatar answered Sep 28 '22 01:09

0x10203040