微软开发了一个开源跨平台的http库--C++ REST SDK(http://casablanca.codeplex.com/),又名卡萨布兰卡Casablanca,有个电影也叫这个名字,也许这个库的作者很喜欢这个电影吧。从REST SDK这个名字可以看出它是处理rest API的,对REST不了解的童鞋可以点这里和这里,由于REST API的请求支持application/x-www-form-urlencoded、application/json、application/octet-stream等多种编码方式,REST API的返回值都是json形式,很方便返回对象。Casablanca采用c++11开发,集成了PPL和asio,支持异步数据流和web socket,用起来很方便。下面来看看官方的一个例子吧:
#include <cpprest\http_client.h> #include <cpprest\filestream.h> using namespace utility; using namespace web; using namespace web::http; using namespace web::http::client; using namespace concurrency; void TestRequest() { auto fileStream = std::make_shared<concurrency::streams::ostream>(); pplx::task<void> requestTask = concurrency::streams::fstream::open_ostream(U("result.html")).then([=](concurrency::streams::ostream outFile){ *fileStream = outFile; http_client client(U("http://www.bing.com/")); uri_builder builder(U("/search")); builder.append_query(U("q"), U("Casablanca CodePlex")); return client.request(methods::GET, builder.to_string()); }) .then([=](http_response response) { return response.body().read_to_end(fileStream->streambuf()); }).then([=](size_t len){ return fileStream->close(); }); try { requestTask.wait(); } catch (const std::exception& e) { cout << e.what() << endl; } } |
这个例子把从bing.com上查询“Casablanca CodePlex”的内容保存到一个本地文件result.html中,用到了ppl的串行任务。启用了四个异步任务,第一个任务是打开一个文件流,接着,发起了第二个任务,用于发起一个查询请求,然后,第三个任务等待请求的响应,并将响应的结果输入到文件中去,第四个任务是关闭文件流。要注意rest sdk的字符相关的入参是宽字符(wchr_t)。这种处理http的方式让我们处理http的流程变得很清晰,有点小清新^_^,不过,这对于不太熟悉ppl用法的童鞋可能有点难接受,没关系,让我来简化一下,简化成同步方式,看得就更清楚了。
void TestRequest() { auto fileStream = std::make_shared<concurrency::streams::ostream>(); concurrency::streams::ostream outFile = concurrency::streams::fstream::open_ostream(U("result11.html")).get(); *fileStream = outFile; http_client client(L"http://www.bing.com/"); uri_builder builder(L"/search"); builder.append_query(L"q", L"Casablanca CodePlex"); http_response response = client.request(methods::GET, builder.to_string()).get(); response.body().read_to_end(fileStream->streambuf()).get(); fileStream->close().get(); } |