微軟的代號為Casablanca的C++ REST SDK已經基於Apache許可證開源。它被描述為“微軟為了以原生代碼支持基於雲的客戶端/服務器通信所做的努力,采用了現代異步C++ API設計”。該產品使用C++11實現,微軟希望提供一種更簡單的編寫客戶端HTTP代碼的方法。
Casablanca支持多個平台,除了Windows 7、Windows 8之外還支持Linux。微軟的開發人員Artur Laksberg提到,對WinXP和Vista的支持正在開發之中。該產品的另一個亮點是支持異步操作。微軟在公布時提供了一些例子來說明Casablanca的使用,一個是通過HTTP上傳文件,一個是JSON對象的創建。
Windows和Linux上的構建版本都支持以下特性:
- 能夠通過HTTP客戶端創建到服務器的連接,並能發送請求和處理響應。
- 支持URI的構建與使用。
- 能夠構建、解析和序列化JSON值。
- 可以通過流(Stream)和流緩沖(Stream Buffer)對底層介質進行異步的數據讀寫。
Casablanca中有幾種不同的流和流緩沖可供使用:基於內存的生產者/消費者、文件、可以配合STL容器使用的基於內存的流、裸指針流和互操作流。互操作流使得“Casablanca能夠提供兩組類,一組使用異步流到iostream的接口,另一組使用iostream到異步流的接口”。
Linux HTTP客戶端還有些限制,因為它尚不支持HTTPS、代理和認證,但微軟介紹說這些特性會包含在未來的版本中。Casablanca的源代碼放在了CodePlex上,可以在線查看或通過Git獲取,還可以以Zip包形式下載最新的快照版本。
C++ REST SDK 包含在 Casablanca 項目中。Casablanca 是一個 C++ 本地庫,旨在幫助開發者的 C++ 應用程序訪問雲服務。如果你想編寫一個響應式的 C++ 客戶端應用程序,或者是一個可擴展的服務端解決方案,可以試試 Casablanca。除了C++ REST SDK 外,Casablanca 項目還包含 Azure SDK for C++。
C++ REST SDK 中包含了一些工具,可以幫助開發者快速編寫現代、異步、可連接 REST 服務的 C++ 應用程序,遵循C++11 標准,目前支持 Windows 7、Windows 8(包括 Windows Store 和桌面應用)和 Linux。
該 SDK 的主要特性包括:
- 能夠通過 HTTP Client 創建服務器連接,並發送請求、處理響應
- 支持構造和使用 URI(Uniform Resource Identifiers,統一資源標識符)
- 構造、解析和序列化 JSON 值
- 通過 Streams 和 Stream Buffers 從底層介質異步讀取/寫入字節
下面的示例演示了如何上傳文件到 HTTP 服務器:
#include <http_client.h>
#include<filestream.h>
#include <uri.h> using namespace concurrency::streams;
using namespace web::http::client;
using namespace web::http;
int main ()
{
// Open stream to file. file_stream<unsigned char>::open_istream (L"myfile.txt") .then ([](basic_istream<unsigned char> fileStream)
{
// Make HTTP request with the file stream as the body. http_client client (L"http://www.myhttpserver.com");
client.request (methods::PUT, L"myfile", fileStream) .then ([fileStream](http_response response)
{
fileStream.close ();
// Perform actions here to inspect the HTTP response... if(response.status_code () == status_codes::OK)
{
}
});
});
return 0;
}
下面的示例演示了如何構建並遍歷 JSON 值:
#include <json.h> int main () { // Create a JSON object. json::value obj; obj[L"key1"] = json::value::boolean (false); obj[L"key2"] = json::value::number (44); obj[L"key3"] = json::value::number (43.6); obj[L"key4"] = json::value::string(U("str")); // Loop over each element in the object. for(auto iter = obj.cbegin (); iter != obj.cend (); ++iter) { // Make sure to get the value as const reference otherwise you will end up copying // the whole JSON value recursively which can be expensive if it is a nested object. const json::value &str = iter->first; const json::value &v = iter->second; // Perform actions here to process each string and value in the JSON object... wprintf (L"String:%s", str.as_string ()); wprintf (L"Value:%s", v.to_string ()); } return 0; }
詳細信息:The C++ REST SDK ("Casablanca")
Using the Microsoft C++ REST SDK