微軟的代號為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")