以下是C++實現HTTPClient的基本步驟:
#include <iostream>
#include <string>
#include <sstream>
#include <curl/curl.h>
class HTTPClient {
public:
HTTPClient();
~HTTPClient();
std::string get(const std::string& url);
private:
static size_t writeCallback(void* contents, size_t size, size_t nmemb, void* userp);
CURL* curl;
};
HTTPClient::HTTPClient() {
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
}
HTTPClient::~HTTPClient() {
curl_easy_cleanup(curl);
curl_global_cleanup();
}
std::string HTTPClient::get(const std::string& url) {
std::string response;
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
CURLcode res = curl_easy_perform(curl);
if(res != CURLE_OK) {
std::cerr << "Error during GET request: " << curl_easy_strerror(res) << std::endl;
}
}
return response;
}
size_t HTTPClient::writeCallback(void* contents, size_t size, size_t nmemb, void* userp) {
size_t realsize = size * nmemb;
std::string* response = (std::string*)userp;
response->append((char*)contents, realsize);
return realsize;
}
int main() {
HTTPClient client;
std::string url = "https://jsonplaceholder.typicode.com/posts/1";
std::string response = client.get(url);
std::cout << "Response: " << response << std::endl;
return 0;
}
通過以上步驟,我們可以實現一個簡單的C++ HTTPClient,可以用來發送GET請求并獲取響應數據。