C++如何调用REST API_C++网络编程与REST接口调用
C++可通过libcurl库实现REST API调用,结合nlohmann/json解析响应数据。首先使用libcurl发送HTTP请求,设置URL、请求方法、头部及回调函数处理响应;对于POST请求需附加JSON数据并设置Content-Type头;最后利用nlohmann/json库解析返回的JSON内容,适用于高性能场景。

在C++中调用REST API并不像Python或J*aScript那样有丰富的内置支持,但通过合适的库和方法,完全可以实现高效、稳定的HTTP通信。关键在于选择合适的网络库来处理底层传输,并手动构建符合REST规范的请求与解析响应。
使用libcurl进行HTTP请求
libcurl 是C/C++中最常用的网络库之一,支持HTTP、HTTPS等多种协议,非常适合调用REST接口。
以下是一个使用libcurl发送GET请求的例子:
#include <iostream>
#include <string>
#include <curl/curl.h>
<p>// 回调函数:接收响应数据
size_t WriteCallback(void<em> contents, size_t size, size_t nmemb, std::string</em> response) {
size_t totalSize = size <em> nmemb;
response->append((char</em>)contents, totalSize);
return totalSize;
}</p><p>int main() {
CURL* curl;
CURLcode res;
std::string readBuffer;</p><pre class='brush:php;toolbar:false;'>curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, "https://jsonplaceholder.typicode.com/posts/1");
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_strerror(res) << std::endl;
} else {
std::cout << "响应: " << readBuffer << std::endl;
}
curl_easy_cleanup(curl);
}
return 0;}
星绘
豆包旗下 AI 写真、P 图、换装和视频生成
404
查看详情
编译时需要链接libcurl:
g++ -o rest_example rest_example.cpp -lcurl发送POST请求并携带JSON数据
调用REST API常需提交JSON数据,例如创建资源。可以通过设置请求头和请求体实现。
#include <string>
#include <curl/curl.h>
<p>size_t WriteCallback(void<em> contents, size_t size, size_t nmemb, std::string</em> response) {
size_t totalSize = size <em> nmemb;
response->append((char</em>)contents, totalSize);
return totalSize;
}</p><p>int main() {
CURL* curl;
CURLcode res;
std::string readBuffer;
std::string postData = R"({"title": "foo", "body": "bar", "userId": 1})";</p><pre class='brush:php;toolbar:false;'>curl = curl_easy_init();
if (curl) {
struct curl_slist* headers = nullptr;
headers = curl_slist_append(headers, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_URL, "https://jsonplaceholder.typicode.com/posts");
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postData.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
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 << "POST请求失败: " << curl_easy_strerror(res) << std::endl;
} else {
std::cout << "响应: " << readBuffer << std::endl;
}
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
}
return 0;}
处理JSON响应(配合nlohmann/json)
大多数REST API返回JSON格式数据,推荐使用 nlohmann/json 库来解析。
先安装该头文件库(可通过vcpkg或直接包含单个头文件):
#include <iostream> #include <string> #include<curl/curl.h> #include <nlohmann/json.hpp> <p>using json = nlohmann::json;</p><p>size_t WriteCallback(void<em> contents, size_t size, size_t nmemb, std::string</em> response) { response->append((char<em>)contents, size </em> nmemb); return size * nmemb; }</p><p>int main() { CURL* curl; CURLcode res; std::string response;</p><pre class='brush:php;toolbar:false;'>curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, "https://jsonplaceholder.typicode.com/posts/1"); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); res = curl_easy_perform(curl); if (res == CURLE_OK) { try { json j = json::parse(response); std::cout << "ID: " << j["id"] << ", Title: " << j["title"] << std::endl; } catch (const std::exception& e) { std::cerr << "JSON解析错误: " << e.what() << std::endl; } } else { std::cerr << "请求失败: " << curl_easy_strerror(res) << std::endl; } curl_easy_cleanup(curl); } return 0;
}
基本上就这些。C++调用REST API的核心是:用libcurl发请求,自己构造URL、头、体,再用JSON库解析结果。虽然代码比脚本语言多一点,但控制力更强,适合性能要求高的场景。
以上就是C++如何调用REST API_C++网络编程与REST接口调用的详细内容,更多请关注其它相关文章!

<curl/curl.h>
#include <nlohmann/json.hpp>
<p>using json = nlohmann::json;</p><p>size_t WriteCallback(void<em> contents, size_t size, size_t nmemb, std::string</em> response) {
response->append((char<em>)contents, size </em> nmemb);
return size * nmemb;
}</p><p>int main() {
CURL* curl;
CURLcode res;
std::string response;</p><pre class='brush:php;toolbar:false;'>curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, "https://jsonplaceholder.typicode.com/posts/1");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
res = curl_easy_perform(curl);
if (res == CURLE_OK) {
try {
json j = json::parse(response);
std::cout << "ID: " << j["id"] << ", Title: " << j["title"] << std::endl;
} catch (const std::exception& e) {
std::cerr << "JSON解析错误: " << e.what() << std::endl;
}
} else {
std::cerr << "请求失败: " << curl_easy_strerror(res) << std::endl;
}
curl_easy_cleanup(curl);
}
return 0;