使用c++编写一个基于libcurl的http传输的类
时间: 2023-08-14 09:04:09 浏览: 135
以下是一个简单的基于libcurl的HTTP传输类的示例代码:
#include <string>
#include <curl/curl.h>
class HttpTransfer {
public:
HttpTransfer() {
curl_global_init(CURL_GLOBAL_ALL);
curl_ = curl_easy_init();
}
~HttpTransfer() {
if (curl_ != nullptr) {
curl_easy_cleanup(curl_);
curl_ = nullptr;
}
curl_global_cleanup();
}
void SetUrl(const std::string& url) {
url_ = url;
}
void SetTimeout(long timeout) {
timeout_ = timeout;
}
void SetHeaders(const std::vector<std::string>& headers) {
headers_ = headers;
}
void SetBody(const std::string& body) {
body_ = body;
}
CURLcode Get(std::string& response) {
return transfer("GET", response);
}
CURLcode Post(std::string& response) {
return transfer("POST", response);
}
private:
CURL* curl_;
std::string url_;
long timeout_ = 10;
std::vector<std::string> headers_;
std::string body_;
static size_t write_callback(char* ptr, size_t size, size_t nmemb, void* userdata) {
std::string* response = static_cast<std::string*>(userdata);
response->append(ptr, size * nmemb);
return size * nmemb;
}
CURLcode transfer(const std::string& method, std::string& response) {
if (curl_ == nullptr) {
return CURLE_FAILED_INIT;
}
curl_easy_setopt(curl_, CURLOPT_URL, url_.c_str());
curl_easy_setopt(curl_, CURLOPT_TIMEOUT, timeout_);
curl_easy_setopt(curl_, CURLOPT_CUSTOMREQUEST, method.c_str());
curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, headers_.data());
curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, body_.c_str());
curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &response);
CURLcode res = curl_easy_perform(curl_);
return res;
}
};
这个类提供了设置URL、超时、HTTP头、HTTP主体和发送GET或POST请求的函数。使用方法如下:
HttpTransfer transfer;
transfer.SetUrl("https://www.example.com/");
transfer.SetTimeout(30);
std::vector<std::string> headers = {"Content-Type: application/json"};
transfer.SetHeaders(headers);
std::string body = "{\"key\": \"value\"}";
transfer.SetBody(body);
std::string response;
CURLcode res = transfer.Post(response);
if (res == CURLE_OK) {
// 处理响应
} else {
// 处理错误
}
注意在使用curl_easy_cleanup函数清理curl句柄之前,应该先判断curl句柄是否为nullptr,以避免野指针的问题。