当前位置: 首页 > 工具软件 > Casablanca > 使用案例 >

C++ REST SDK(Casablanca)

金子平
2023-12-01

简介

微软开发了一个开源跨平台的http库--C++ REST SDK,又名卡萨布兰卡Casablanca。由于REST API的请求支持application/x-www-form-urlencoded、application/json、application/octet-stream等多种编码方式,REST API的返回值都是json形式,很方便返回对象。Casablanca采用c++11开发,集成了PPL和asio,支持异步数据流和web socket.

下载地址:https://github.com/Microsoft/cpprestsdk

头文件

#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
#include <cpprest/uri.h>
#include <cpprest/json.h>

using namespace utility;
using namespace web;
using namespace web::http;
using namespace web::http::client;
using namespace concurrency::streams;

相关对象和函数介绍

http_client_config

客户端配置信息,包含超时时间等

http_client_config m_ClientConfig;
m_ClientConfig.set_timeout(utility::seconds(10));

uri

统一资源标志符,本质上属于宽字符

uri m_Uri;
utility::string_t address = U("http://localhost:34568");//主机地址
m_Uri = http::uri(address);

资源连接地址会经常包含资源路径和其它参数,可以使用uri_builder进行拼接

uri_builder builder;
builder.append_path(L"search"); //添加URL
builder.append_query(L"q", L"Casablanca CodePlex"); //添加url参数

http_client

客户端,需要它发起http请求,构造函数如下

/// <summary>
    /// Creates a new http_client connected to specified uri.
    /// </summary>
    /// <param name="base_uri">A string representation of the base uri to be used for all requests. Must start with
    /// either "http://" or "https://"</param>
    _ASYNCRTIMP http_client(const uri& base_uri);

    /// <summary>
    /// Creates a new http_client connected to specified uri.
    /// </summary>
    /// <param name="base_uri">A string representation of the base uri to be used for all requests. Must start with
    /// either "http://" or "https://"</param> <param name="client_config">The http client configuration object
    /// containing the possible configuration options to initialize the <c>http_client</c>. </param>
    _ASYNCRTIMP http_client(const uri& base_uri, const http_client_config& client_config);

request

请求命令,最常用的格式如下:

/// <summary>
/// Asynchronously sends an HTTP request.
/// </summary>
/// <param name="mtd">HTTP request method.</param>
/// <param name="path_query_fragment">String containing the path, query, and fragment, relative to the http_client's
 base URI.</param> 
/// <param name="body_data">The data to be used as the message body, represented using the json object library.</param> 
/// <param name="token">Cancellation token for cancellation of this request operation.</param>
/// <returns>An asynchronous operation that is completed once a response from the request is received.</returns>

    pplx::task<http_response> request(const method& mtd,
                                      const utility::string_t& path_query_fragment,
                                      const json::value& body_data,
                                      const pplx::cancellation_token& token =           pplx::cancellation_token::none()
                                      )

http_response

响应消息,包含结果和返回值

实例代码如下:

//HTTP客户端配置,用于设置创建http_client实例的可配置选项。
http_client_config m_ClientConfig;
m_ClientConfig.set_timeout(utility::seconds(30));
//uri参数定义
uri m_Uri;
utility::string_t address = U("http://localhost:34568");//主机地址
m_Uri = http::uri(address);
//增加一些URL,可以用uri_builder来做拼接
uri_builder builder;
builder.append_path(L"search"); //添加URL
builder.append_query(L"q", L"Casablanca CodePlex"); //添加url参数
//request body,一般是json或者二进制格式,此处是json
json::value reqMsg;
reqMsg[U("1")] = json::value::string(U("A"));
reqMsg[U("2")] = json::value::string(U("B"));
reqMsg[U("3")] = json::value::string(U("C"));
//客户端,发起http请求
http_client client(m_Uri, m_ClientConfig);
http_response response = client.request(methods::POST, builder.to_string(), reqMsg).get();//get()方法会阻塞等待异步线程完成操作
//http_response对象来处理响应

if (response.status_code() == status_codes::OK)
{
	try
	{
		ucout << "responsePost: " << response.to_string() << std::endl;
		const json::value &jv = response.extract_json().get();
	}
	catch (const std::exception &e)
	{
		ucout << e.what() << std::endl;
	}
}

 类似资料: