Capture header from response
mulderp opened this issue · 1 comments
mulderp commented
Hello,
I would like to capture the header data from a response.
In the curl documentation I think it should be possible by using HEADERDATA and I found an example here:
https://gist.github.com/whoshuu/2dc858b8730079602044
However, with curlpp I was not sure how to apply this.
I tried:
myRequest.setOpt(cURLpp::Options::HeaderFunction(f));
but not sure how to define f, and if there would be a similar way to write to stream like the normal response body:
myRequest.setOpt(cURLpp::Options::WriteStream(&resp));
sgallou commented
Hello,
you can use lambda, like to get the full header buffer :
std::string headersBuffer;
m_request.setOpt(curlpp::options::HeaderFunction(
[&headersBuffer](char* ptr, size_t size, size_t nbItems)
{
const auto incomingSize = size * nbItems;
headersBuffer.append(ptr, incomingSize);
return incomingSize;
}));
And you can use this function to organize the buffer as a map of header :
std::map<std::string, std::string> CCurlppHttpRestRequest::formatResponseHeaders(const std::string& headersBuffer) const
{
std::vector<std::string> headerKeyValues;
split(headerKeyValues, headersBuffer, boost::is_any_of("\n"), boost::algorithm::token_compress_on);
std::map<std::string, std::string> responseHeaders;
for (const auto& headerKeyValue : headerKeyValues)
{
const auto separatorIterator = headerKeyValue.find(':');
if (separatorIterator == std::string::npos)
continue;
// Http headers are not case-sensitive
// Make all lower to facilitate search and comparison
auto key = headerKeyValue.substr(0, separatorIterator);
boost::to_lower(key);
auto value = headerKeyValue.substr(separatorIterator + 1, std::string::npos);
boost::to_lower(value);
responseHeaders[key] = value;
}
return responseHeaders;
}
Hope this help