对于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)响应并检索身体?
发布于 2017-02-01 08:03:57
事实证明,这样做非常简单,即使是异步的:
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-01-31 13:35:24
通过分析文档,第五例展示了如何设置回调以获得响应:
// 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图书馆解析它。
https://stackoverflow.com/questions/41958236
复制相似问题