Example of using libcurl library

libcurl

libcurlIt is a powerful cross-platform network transmission library that supports multiple protocols, including HTTP, FTP, SMTP, etc., and provides an easy-to-use API.

Install

ubuntu18.04platform installation

sudo apt-get install libcurl4-openssl-dev

example

This example sends a simple HTTP GET request using the libcurl library and saves the response data in the response string.

#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;
}

Compile and run

g++ example.cpp -lcurl -o example
./example

Data Display

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>

Guess you like

Origin blog.csdn.net/Star_ID/article/details/131809083