使用curlpp发布和接收JSON负载

10

使用curlpp C++包装器来发送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)响应并检索正文内容?

2个回答

18

事实证明,即使是异步地进行,这也相当简单:

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

3
你该如何执行这个庞然大物? - kroiz
很抱歉,我不理解这个问题。这是一个孤立的C++函数,需要与STL和curlpp一起编译和链接。您可以编写单元测试、应用程序或将其嵌入现有代码中以测试运行它,就像处理其他函数一样。STL通常可用,curlpp可以按照C++编译和链接的标准方式进行编译和链接到二进制文件中。 - Oleg Sklyar
2
我的意思是我希望有一个调用它的例子,因为我不理解语法,例如可以简单地这样:invoke("www.example.com", "param1=value"); - kroiz

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


已经找到那一位了,但感谢您提醒我使用分块技术。对于我来说不太清楚的是如何提交请求,不过...使用一个读取器(对应响应的写入器)或许是可以的。需要尝试一下。 - Oleg Sklyar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接