9

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

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

4

2 回答 2

16

事实证明这是相当简单的,即使是异步的:

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);
}
于 2017-02-01T08:03:57.383 回答
1

通过分析文档,第五个例子展示了如何设置回调来获取响应:

// 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 库对其进行解析。

于 2017-01-31T13:35:24.043 回答