使用curlpp发布和接收JSON负载

Ole*_*yar 4 c++ json http-post curlpp

使用curlppC ++包装器,libcurl如何为发布请求指定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();
Run Code Online (Sandbox Code Playgroud)

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

Ole*_*yar 5

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

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 你如何处决这个庞然大物? (3认同)
  • 我的意思是我喜欢一个调用它的示例,因为我不理解语法,例如很简单:invoke("www.example.com", "param1=value"); (2认同)