Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Capture header from response #125

Open
mulderp opened this issue Jul 30, 2021 · 1 comment
Open

Capture header from response #125

mulderp opened this issue Jul 30, 2021 · 1 comment

Comments

@mulderp
Copy link

mulderp commented Jul 30, 2021

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
Copy link
Collaborator

sgallou commented Aug 5, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants