C++ REST SDK(Casablanca)

简介

微软开发了一个开源跨平台的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;
	}
}

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C++并不是一种直接支持RESTful的编程语言,但是可以使用第三方库来实现RESTful风格的开发。在C++中,可以使用一些流行的HTTP客户端库(如Curl、cpprestsdk等)来发送HTTP请求和处理响应,从而实现与RESTful API的交互。 C++ REST SDK(又称为Casablanca)是一个开源的C++库,提供了一套用于构建基于HTTP的客户端和服务器的工具和功能。它支持异步操作、URI路由、JSON序列化和反序列化等功能,使得在C++中开发RESTful应用变得更加简单。 使用C++ REST SDK,你可以通过创建HTTP客户端对象来发送HTTP请求,并处理服务器返回的响应。你可以指定请求的方法(GET、POST、PUT等)、URL、请求头、请求体等信息,并且可以异步地发送请求并处理响应。 以下是使用C++ REST SDK发送GET请求的示例代码: ```cpp #include <cpprest/http_client.h> #include <cpprest/filestream.h> using namespace web; using namespace web::http; using namespace web::http::client; int main() { // 创建HTTP客户端对象 http_client client(U("http://example.com")); // 创建HTTP请求 http_request request(methods::GET); // 发送请求并异步获取响应 client.request(request).then([](http_response response) { // 处理响应 if (response.status_code() == status_codes::OK) { // 读取响应内容 return response.extract_string(); } else { // 处理错误 throw std::runtime_error("HTTP request failed"); } }).then([](utility::string_t response_body) { // 处理响应内容 std::cout << "Response: " << response_body << std::endl; }).wait(); return 0; } ``` 这是一个简单的示例,你可以根据具体的需求和API文档来构建更复杂的RESTful应用。当然,除了C++ REST SDK,还有其他一些第三方库也可以用于在C++中实现RESTful风格的开发,你可以根据自己的需求选择合适的库进行开发。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值