使用 curlpp 发送和接收 JSON 负载

Posting and receiving JSON payload with curlpp

使用 curlpp C++ 包装器 libcurl 如何为 post 请求指定 JSON 有效载荷以及如何接收 JSON 有效载荷回复?我从这里去哪里:

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();

那么,如何等待 (JSON) 响应并检索正文?

通过分析文档,fifth example 展示了如何设置回调以获得响应:

// Set the writer callback to enable cURL to write result in a memory area
curlpp::types::WriteFunctionFunctor functor(WriteMemoryCallback);
curlpp::options::WriteFunction *test = new curlpp::options::WriteFunction(functor);
request.setOpt(test);

回调定义为

size_t WriteMemoryCallback(char* ptr, size_t size, size_t nmemb)

由于响应可以成块到达,因此可以多次调用。响应完成后,使用 JSON library 对其进行解析。

事实证明这是相当简单的,甚至是异步的:

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);
}