libcurl
libcurl
是一个功能强大的跨平台网络传输库,支持多种协议,包括HTTP、FTP、SMTP等,同时提供了易于使用的API。
安装
ubuntu18.04
平台安装
sudo apt-get install libcurl4-openssl-dev
实例
这个示例使用libcurl库发送一个简单的HTTP GET请求,并将响应数据保存在response字符串中。
#include <iostream>
#include <curl/curl.h>
// 回调函数,用于处理HTTP响应数据
size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* response)
{
size_t totalSize = size * nmemb;
response->append(static_cast<char*>(contents), totalSize);
return totalSize;
}
int main()
{
CURL* curl;
CURLcode res;
std::string response;
// 初始化curl
curl = curl_easy_init();
if (curl)
{
// 设置URL
curl_easy_setopt(curl, CURLOPT_URL, "http://baidu.com");
// 设置接收响应数据的回调函数
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
// 执行HTTP GET请求
res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
}
else
{
// 打印响应数据
std::cout << "Response: " << response << std::endl;
}
// 清理curl
curl_easy_cleanup(curl);
}
return 0;
}
编译运行
g++ example.cpp -lcurl -o example
./example
数据显示
root@sjn:/home/libcurltest# ./example
Response: <html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>bfe/1.0.8.18</center>
</body>
</html>