以下是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请求并获取响应数据。