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)响应并检索正文?
事实证明,这样做相当简单,甚至是异步的:
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)
| 归档时间: |
|
| 查看次数: |
3146 次 |
| 最近记录: |