c++jsonhttp-postcurlpp

Posting and receiving JSON payload with curlpp


With the curlpp C++ wrapper for libcurl how do I specify JSON payload for a post request and how can I receive JSON payload in response? Where do I go from here:

std::string json("{}");

std::list<std::string> header;
header.push_back("Content-Type: application/json");

cURLpp::Easy r;
r.setOpt(new curlpp::options::Url(url));
r.setOpt(new curlpp::options::HttpHeader(header));
// set payload from json?
r.perform();

Then, how do I await for a (JSON) response and retrieve the body?


Solution

  • Turns out this is fairly straightforward to do, even asynchronously:

    std::future<std::string> invoke(std::string const& url, std::string const& body) {
      return std::async(std::launch::async,
        [](std::string const& url, std::string const& body) mutable {
          std::list<std::string> header;
          header.push_back("Content-Type: application/json");
    
          curlpp::Cleanup clean;
          curlpp::Easy r;
          r.setOpt(new curlpp::options::Url(url));
          r.setOpt(new curlpp::options::HttpHeader(header));
          r.setOpt(new curlpp::options::PostFields(body));
          r.setOpt(new curlpp::options::PostFieldSize(body.length()));
    
          std::ostringstream response;
          r.setOpt(new curlpp::options::WriteStream(&response));
    
          r.perform();
    
          return std::string(response.str());
        }, url, body);
    }