CPP REST SDK是微软开源的基于PPL的异步http client,网络层使用的是Boost.Asio,跨平台,并且支持json解析,在使用CPP REST SDK之前要确保已经安装了boost和openssl
安装boost和openssl
yum install boost-devel -y
yum install openssl-devel -y
安装cpprestsdk
git clone https:斜杠github.com/microsoft/cpprestsdk
cd cpprestsdk
git submodule update --init
mkdir build && cd build
cmake ..
make -j4
make install
报错:
cpprestsdk/Release/tests/functional/http/listener/listener_construction_tests.cpp:529:17: error: ‘class boost::asio::ssl::context’ has no member named ‘use_certificate_chain’; did you mean ‘use_certificate_file’?
原因:yum安装boost只有1.53版本,要手动安装1.63.0版本
解决:手动安装boost
源码下载:https:斜杠boostorg.jfrog.io/artifactory/main/release/
cd boost_1_63_0
./bootstrap.sh
./b2
./b2 install
使用示例
从 HTTP GET 响应提取 JSON 数据
// Retrieves a JSON value from an HTTP request.
pplx::task<void> RequestJSONValueAsync()
{
// TODO: To successfully use this example, you must perform the request
// against a server that provides JSON data.
// This example fails because the returned Content-Type is text/html and not application/json.
http_client client(L"https:斜杠abc.def.com");
return client.request(methods::GET).then([](http_response response) -> pplx::task<json::value>
{
if(response.status_code() == status_codes::OK)
{
return response.extract_json();
}
// Handle error cases, for now return empty json value...
return pplx::task_from_result(json::value());
})
.then([](pplx::task<json::value> previousTask)
{
try
{
const json::value& v = previousTask.get();
// Perform actions here to process the JSON value...
}
catch (const http_exception& e)
{
// Print error.
wostringstream ss;
ss << e.what() << endl;
wcout << ss.str();
}
});
/* Output:
Content-Type must be application/json to extract (is: text/html)
*/
}