REST是一種架構風格,利用HTTP協議中的GET、POST、PUT、DELETE等方法與服務器交互,通常用于客戶端和服務器之間的數據交換。REST API通信的核心在于定義資源,客戶端通過URL訪問服務器上的資源,并通過HTTP方法操作這些資源。

3. C++構建服務端和C#構建客戶端實現雙向交互

1. C++構建Restful服務端

Boost 是一個廣受歡迎的 C++ 開源庫集合,提供了諸多用于跨平臺開發的實用工具。Boost 涵蓋了從算法到 I/O、正則表達式、容器和多線程等多種功能,尤其適合構建高性能的服務器、網絡和系統應用。我們就使用 Boost庫構建一個 RESTful 風格的 C++ Web API。

1.1 Boost庫的核心依賴

我們主要使用兩個核心庫:

  1. 1. Boost.Asio:提供跨平臺的異步 I/O 功能,適用于構建高效的 TCP、UDP 等網絡應用。
  2. 2.?Boost.Beast:基于 Boost.Asio 實現的 HTTP 和 WebSocket 協議庫,簡化了 RESTful API 的構建。

通過vcpkg命令安裝 Boost.Asio庫

vcpkg install boost-asio

通過vcpkg命令安裝 Boost.Beast庫

vcpkg install boost-beast

1.2 構建 RESTful C++ Web API

使用 Boost.Beast 構建一個簡單的 RESTful API 服務,支持基本的 CRUD(創建、讀取、更新、刪除)操作。我們的 API 將運行在端口 8080 上,支持以下路徑:

1.3 編碼實現服務端代碼

#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <iostream>
#include <string>
#include <thread>

namespace asio = boost::asio;
namespace beast = boost::beast;
namespace http = beast::http;
using tcp = asio::ip::tcp;

std::string data_store = "Sample data"; // 簡單的數據存儲

// 處理 HTTP 請求的函數
void handle_request(const http::request<http::string_body>& req, http::response<http::string_body>& res) {
if (req.method() == http::verb::get && req.target() == "/api/data") {
res.result(http::status::ok);
res.set(http::field::content_type, "application/json");
res.body() = R"({"data": ")" + data_store + R"("})";
}
else if (req.method() == http::verb::post && req.target() == "/api/data") {
data_store = req.body();
res.result(http::status::created);
res.set(http::field::content_type, "application/json");
res.body() = R"({"message": "Data created"})";
}
else if (req.method() == http::verb::put && req.target() == "/api/data") {
data_store = req.body();
res.result(http::status::ok);
res.set(http::field::content_type, "application/json");
res.body() = R"({"message": "Data updated"})";
}
else if (req.method() == http::verb::delete_ && req.target() == "/api/data") {
data_store.clear();
res.result(http::status::ok);
res.set(http::field::content_type, "application/json");
res.body() = R"({"message": "Data deleted"})";
}
else {
res.result(http::status::not_found);
res.set(http::field::content_type, "application/json");
res.body() = R"({"error": "Resource not found"})";
}
res.prepare_payload();
}

// 會話處理
void session(tcp::socket socket) {
beast::flat_buffer buffer;
http::request<http::string_body> req;
http::response<http::string_body> res;

try {
http::read(socket, buffer, req);
handle_request(req, res);
http::write(socket, res);
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
}

// 主程序啟動服務器
int main() {
try {
asio::io_context ioc;
tcp::acceptor acceptor(ioc, tcp::endpoint(tcp::v4(), 8080));
std::cout << "Server running on http://localhost:8080\n";

while (true) {
tcp::socket socket(ioc);
acceptor.accept(socket);
std::thread(&session, std::move(socket)).detach();
}
} catch (const std::exception& e) {
std::cerr << "Server error: " << e.what() << std::endl;
}
return 0;
}

1.4 啟動服務程序

訪問地址:http://localhost:8080/

訪問地址:http://localhost:8080/api/data

2. 構建C#客戶端調用C++ RESTful API

使用 C# 的 HttpClient 調用 C++ RESTful API 并進行數據交互。

2.1 編碼實現客戶端代碼

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace CppWebApiClient
{
class Program
{
private static readonly HttpClient client = new HttpClient();

static async Task Main(string[] args)
{
// GET 請求
HttpResponseMessage response = await client.GetAsync("http://localhost:8080/api/data");
string getData = await response.Content.ReadAsStringAsync();
Console.WriteLine("GET Response: " + getData);

// POST 請求
string newData = "\"New sample data\"";
response = await client.PostAsync("http://localhost:8080/api/data", new StringContent(newData, Encoding.UTF8, "application/json"));
Console.WriteLine("POST Response: " + await response.Content.ReadAsStringAsync());

// PUT 請求
string updateData = "\"Updated data\"";
response = await client.PutAsync("http://localhost:8080/api/data", new StringContent(updateData, Encoding.UTF8, "application/json"));
Console.WriteLine("PUT Response: " + await response.Content.ReadAsStringAsync());

// DELETE 請求
response = await client.DeleteAsync("http://localhost:8080/api/data");
Console.WriteLine("DELETE Response: " + await response.Content.ReadAsStringAsync());

Console.ReadKey();
}
}
}

啟動客戶端程序

訪問地址:http://localhost:8080/api/data

數據已被刪除。

4. C++構建客戶端和C#構建服務端實現雙向交互

我們將通過兩個部分來構建一個RESTful風格的API服務(使用ASP.NET Core WebAPI)以及如何在C++中調用這個WebAPI。

1. 構建ASP.NET Core WebAPI服務

  1. 創建ASP.NET Core WebAPI項目
dotnet new webapi -n MyApi
cd MyApi

2.?定義一個簡單的Controller?我們創建一個簡單的Controller?ProductsController.cs,提供幾個GET和POST的接口

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace MyApi.Controllers
{
public class ProductRequest
{
public string Product { get; set; }
}
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
// 這是一個存儲產品的示例
private static readonly List<string> Products = new List<string>
{
"Product1",
"Product2",
"Product3"
};
// 獲取所有產品
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return Ok(Products);
}
// 獲取單個產品
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
if (id < 0 || id >= Products.Count)
{
return NotFound();
}
return Ok(Products[id]);
}
// 創建新產品
[HttpPost]
public ActionResult Post([FromBody] ProductRequest product)
{
if (string.IsNullOrEmpty(product?.Product))
{
return BadRequest("Product cannot be empty");
}

Products.Add(product.Product);
return CreatedAtAction(nameof(Get), new { id = Products.Count - 1 }, product);
}
}
}

3.?運行API?在命令行中,運行以下命令啟動API服務器:

dotnet run

2. 構建C++客戶端調用WebAPI

現在,我們已經創建了一個基本的WebAPI服務。接下來,我們將在C++中編寫代碼,通過HTTP請求來調用這個WebAPI。為了發送HTTP請求,C++沒有內置的庫,因此我們將使用一些第三方庫,如libcurl

  1. 安裝libcurl庫?可以從libcurl官網[1]下載并安裝。或者通過vcpkg安裝?vcpkg install curl

2.?C++代碼:使用libcurl調用WebAPI在C++中,我們將使用libcurl庫來發送HTTP請求。

#include <iostream>
#include <string>
#include <curl/curl.h>
// 回調函數,用于處理HTTP響應數據
size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
size_t totalSize = size * nmemb;
((std::string*)userp)->append((char*)contents, totalSize);
return totalSize;
}
// GET請求
void GetProducts() {
CURL* curl;
CURLcode res;
std::string readBuffer;
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:5056/api/products");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
// 執行請求
res = curl_easy_perform(curl);
// 檢查請求是否成功
if (res != CURLE_OK) {
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
}
else {
std::cout << "Response: " << readBuffer << std::endl;
}
curl_easy_cleanup(curl);
}
curl_global_cleanup();
}

// POST請求
void AddProduct(const std::string& product) {
CURL* curl;
CURLcode res;
std::string readBuffer;
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if (curl) {
// 設置URL
curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:5056/api/products");
// 設置HTTP頭
struct curl_slist* headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
// 設置POST數據
std::string jsonData = "{\"product\":\"" + product + "\"}";
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonData.c_str());
// 處理響應
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
// 執行請求
res = curl_easy_perform(curl);
// 檢查請求是否成功
if (res != CURLE_OK) {
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
}
else {
std::cout << "Response: " << readBuffer << std::endl;
}
curl_easy_cleanup(curl);
curl_slist_free_all(headers);
}
curl_global_cleanup();
}
int main() {
// 獲取所有產品
GetProducts();
// 添加新產品
AddProduct("Product4");
// 獲取所有產品,查看是否添加成功
GetProducts();
int i;
std::cin >> i;
return 0;
}

3.?編譯并運行C++代碼

5. 注意事項

  1. 安全性:在生產環境中,請使用SSL證書,確保API通信的安全性。在開發環境中可以臨時禁用SSL驗證。
  2. 數據格式:通常REST API使用JSON格式傳遞數據,便于解析。
  3. 錯誤處理:在生產中,要添加錯誤處理,捕獲網絡問題和API錯誤狀態碼,確保程序穩定性。

6. 應用場景

7. 優缺點

8. 總結

REST API 提供了一種靈活且標準化的通信方式,能夠在不同語言和平臺間實現通信。通過本文的示例代碼,C++ 和 C# 程序可以借助 REST API 實現數據交互。這種方法尤其適合分布式應用和微服務架構的設計。在下一篇中,我們將介紹gRPC,這是一個高效的跨平臺通信協議,非常適合高性能需求的場景。

文章轉自微信公眾號@dotnet研習社

上一篇:

構建現代RESTful API:C#中的關鍵標準和最佳實踐

下一篇:

把 C# 里的 HttpClient 封裝起來,告別復雜的配置,讓 Restful API 調用更輕松更高效
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費