#include <iostream>
#include <string>
#include <curl/curl.h>
// 定义一个回调函数,用于处理从服务器接收到的数据
size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) {
size_t totalSize = size * nmemb;
userp->append((char*)contents, totalSize);
return totalSize;
}
class RestClient {
public:
// 发送GET请求
static std::string Get(const std::string& url) {
CURL* curl;
CURLcode res;
std::string responseString;
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &responseString);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if (res != CURLE_OK) {
return "Error: " + std::string(curl_easy_strerror(res));
}
}
return responseString;
}
// 发送POST请求
static std::string Post(const std::string& url, const std::string& postData) {
CURL* curl;
CURLcode res;
std::string responseString;
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postData.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &responseString);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if (res != CURLE_OK) {
return "Error: " + std::string(curl_easy_strerror(res));
}
}
return responseString;
}
};
int main() {
// 示例:发送GET请求
std::string getResponse = RestClient::Get("https://jsonplaceholder.typicode.com/posts/1");
std::cout << "GET Response:\n" << getResponse << std::endl;
// 示例:发送POST请求
std::string postData = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";
std::string postResponse = RestClient::Post("https://jsonplaceholder.typicode.com/posts", postData);
std::cout << "POST Response:\n" << postResponse << std::endl;
return 0;
}
依赖库:
libcurl 库来处理 HTTP 请求。你需要确保在编译时链接 libcurl 库。回调函数 WriteCallback:
std::string 中。RestClient 类:
Get 和 Post,分别用于发送 GET 和 POST 请求。Get 方法接收一个 URL 并返回响应内容。Post 方法接收一个 URL 和 POST 数据,并返回响应内容。main 函数:
RestClient 类发送 GET 和 POST 请求,并打印响应内容。错误处理:
curl_easy_perform 返回错误码,则会返回相应的错误信息。这个示例代码展示了如何使用 C++ 和 libcurl 库来实现简单的 RESTful API 请求。
上一篇:c++ unsigned int
下一篇:c++ string类
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站