使用curlpp
libcurl
的C ++包装器如何为发布请求指定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)响应并检索正文?
答案 0 :(得分: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);
}
答案 1 :(得分:0)
通过分析文档,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进行解析。