2

I am new to C++ and curlpp, and I needed the header response and the response body from the curlpp response, but what is happening is I am getting both the things in the same string, is there any way or any flag which will help me in storing the header response and response body separately.

   std::ostringstream respMsg;

   request.setOpt(new PostFields(body));

   request.setOpt(new PostFieldSize(body.size()));
   request.setOpt(new Header(1));
   request.setOpt(new curlpp::options::WriteStream(&respMsg));

   if (curlpp::infos::ResponseCode::get(request) == 200){
        // success

        std::cout << respMsg.str() << std::endl;

        json data = parse(respMsg.str())

   } else {

      // failure

      std::cout << respMsg.str() << std::endl;

   }

What I am expecting is in "if" part, I just need the json string, but I am getting header response + JSON string, which I am not able to separate, is there any setOPt flag or any way to get both the things separately, NOTE: I also need the header response in else part to print the error message. Any pointers are appreciated. Thanks in advance and sorry for bad English.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
Ashwin
  • 23
  • 3

1 Answers1

0

The easiest way:

You can simply split the response:

std::string response = respMsg.str();
size_t endOfHeader = response.find("\r\n\r\n");

if (endOfHeader != std::string::npos) {
    std::string header = response.substr(0, endOfHeader);
    std::string body = response.substr(endOfHeader + 4);
}

The best way:

If you need only the response body, you can disable the header option using request.setOpt(new Header(0)); or simply removing the line.

if you need the headers too, you can disable the header and use the HeaderFunction option.

std::string headers;

size_t HeaderCallback(char* ptr, size_t size, size_t nmemb)
{
    int totalSize = size * nmemb;
    headers += std::string(ptr, totalSize);
    return totalSize;
}

request.setOpt(curlpp::options::HeaderFunction(HeaderCallback));

You can understand better the options if you read the libcurl API: here. (curlppis just a wrapper to libcurl).

The header_function documentation is here.

lucas.exe
  • 119
  • 3
  • Thanks, this solution is acceptable, but I was expecting that curlpp would be having something like **response.body** which will give me only body and **response.header** which will provide me header. – Ashwin May 29 '19 at 05:48