用c++写一个http的get请求的函数要求传入地址返回结果
以下是一个用C++编写的简单的HTTP GET请求函数,它使用了libcurl库来发送请求并接收响应:
#include <iostream>
#include <curl/curl.h>
// 回调函数,用于处理接收到的响应数据
size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* response)
{
size_t totalSize = size * nmemb;
response->append((char*)contents, totalSize);
return totalSize;
}
std::string httpGetRequest(const std::string& url)
{
CURL* curl;
CURLcode res;
std::string response;
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
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);
res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
}
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return response;
}
int main()
{
std::string url = "https://www.example.com"; // 替换为你要发送GET请求的URL
std::string response = httpGetRequest(url);
std::cout << "Response: " << response << std::endl;
return 0;
}
你可以将上述代码保存为一个.cpp文件,然后使用C++编译器进行编译和运行。记得在编译时链接libcurl库,例如使用-lcurl选项。请注意,你需要先安装libcurl库才能成功编译运行此代码。
这个函数接受一个URL作为参数,发送GET请求,并返回响应结果。在上面的示例中,我们发送了一个GET请求到https://www.example.com并打印了响应结果。你可以根据需要修改URL以发送其他GET请求
原文地址: https://www.cveoy.top/t/topic/hEFG 著作权归作者所有。请勿转载和采集!