要在C++中發送HTTP請求,您可以使用第三方庫,如CURL或Boost.Beast。以下是一個使用CURL發送GET請求的示例:
#include <iostream>
#include <curl/curl.h>
size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* data) {
data->append((char*)contents, size * nmemb);
return size * nmemb;
}
int main() {
CURL* curl;
CURLcode res;
std::string response;
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://www.example.com");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
std::cerr << "Failed to send HTTP request: " << curl_easy_strerror(res) << std::endl;
} else {
std::cout << "Response: " << response << std::endl;
}
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return 0;
}
在這個示例中,我們使用CURL庫來發送一個簡單的GET請求,并將響應打印到控制臺。您可以根據您的需求修改代碼來發送不同類型的HTTP請求,例如POST請求或帶有自定義標頭的請求。