在C++中,處理HTTP請求的響應通常需要使用第三方庫,因為標準庫并不直接支持HTTP請求
sudo apt-get install libcurl4-openssl-dev
http_request.cpp
的文件,并添加以下代碼:#include<iostream>
#include<string>
#include <curl/curl.h>
size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
int main()
{
CURL* curl = curl_easy_init();
if (curl)
{
std::string url = "https://api.example.com/data";
std::string response;
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: "<< curl_easy_strerror(res)<< std::endl;
}
else
{
std::cout << "Response: "<< std::endl<< response<< std::endl;
}
curl_easy_cleanup(curl);
}
return 0;
}
g++ http_request.cpp -o http_request -lcurl
./http_request
這個示例程序將向https://api.example.com/data
發(fā)送一個GET請求,并將響應內(nèi)容輸出到控制臺。你可以根據(jù)需要修改URL和其他libcurl選項。