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!
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With