当前位置:   article > 正文

C++使用HTTP库和框架轻松发送HTTP请求_c++ http库

c++ http库

一、引言

使用C++编程发送HTTP请求通常需要使用第三方的HTTP库或框架。在C++中,有几个受欢迎的HTTP库可供选择,例如Curl、Boost.Beast和cpp-httplib。另外,也可以自己实现socket来发送http请求。

二、使用Curl库发送HTTP请求

(1)安装Curl库

对于Debian/Ubuntu系统:

sudo apt-get install libcurl4-openssl-dev
  • 1

对于RHEL/CentOS系统:

sudo yum install libcurl-devel
  • 1

对于macOS系统:

brew install curl
  • 1

(2)编写Curl代码。编写一个C++代码示例来使用Curl库发送HTTP请求。将以下代码保存为.cpp文件(例如curl.cpp)。

#include <iostream>
#include <curl/curl.h>

int main() {
    // 初始化Curl库
    curl_global_init(CURL_GLOBAL_ALL);

    // 创建Curl句柄
    CURL* curl = curl_easy_init();
    if (!curl) {
        std::cerr << "Failed to initialize Curl." << std::endl;
        return 1;
    }

    // 设置请求的URL
    const char* url = "https://blog.csdn.net/Long_xu";

    // 设置Curl句柄的URL选项
    curl_easy_setopt(curl, CURLOPT_URL, url);

    // 发送GET请求
    CURLcode res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
        std::cerr << "Failed to send HTTP request: " << curl_easy_strerror(res) << std::endl;
        curl_easy_cleanup(curl);
        curl_global_cleanup();
        return 1;
    }

    // 清理Curl句柄和Curl库
    curl_easy_cleanup(curl);
    curl_global_cleanup();

    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

(3)编译和运行代码

g++ curl.cpp -lcurl -o example
  • 1

然后,运行生成的可执行文件:

./example
  • 1

这里只是发送一个简单的GET请求到指定的URL,并打印任何响应数据。可以根据需要对代码进行修改和扩展,例如设置请求头、发送POST请求、处理响应数据等。

三、使用Boost.Beast库发送HTTP请求

(1)安装Boost库。前面有文章介绍了Boost库的安装,这里就不再赘述。

(2)编写Boost.Beast代码。比如beast_example.cpp

#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <iostream>

namespace http = boost::beast::http;

int main() {
    // 创建Boost.Beast I/O上下文
    boost::asio::io_context ioc;

    // 创建TCP解析器
    boost::asio::ip::tcp::resolver resolver(ioc);

    // 解析主机名和端口
    boost::asio::ip::tcp::resolver::results_type endpoints =
        resolver.resolve("blog.csdn.net", "https");

    // 创建SSL上下文
    boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23);

    // SSL连接
    boost::beast::ssl_stream<boost::asio::ip::tcp::socket> stream(ioc, ctx);

    // 连接到服务器
    boost::asio::connect(stream.next_layer(), endpoints.begin(), endpoints.end());

    // SSL握手
    stream.handshake(boost::asio::ssl::stream_base::client);

    // 创建HTTP请求
    http::request<http::string_body> req(http::verb::get, "/Long_xu", 11);
    req.set(http::field::host, "blog.csdn.net");
    req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);

    // 发送HTTP请求
    http::write(stream, req);

    // 接收HTTP响应
    boost::beast::flat_buffer buffer;
    http::response<http::dynamic_body> res;
    http::read(stream, buffer, res);

    // 打印响应状态码和响应体
    std::cout << "Response code: " << res.result_int() << std::endl;
    std::cout << "Response body: " << boost::beast::buffers_to_string(res.body().data()) << std::endl;

    // 关闭SSL连接
    boost::beast::error_code ec;
    stream.shutdown(ec);

    // 如果有错误,打印错误信息
    if (ec && ec != boost::asio::error::eof) {
        std::cerr << "Error: " << ec.message() << std::endl;
        return 1;
    }

    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59

步骤 3: 编译和运行代码

g++ beast_example.cpp -o beast_example -lboost_system -lboost_filesystem -lboost_thread -lboost_iostreams -lssl -lcrypto
  • 1

运行生成的可执行文件:

./beast_example
  • 1

四、使用cpp-httplib库发送HTTP请求

(1)下载cpp-httplib库源代码。要从cpp-httplib的GitHub仓库下载库的源代码:

git clone https://github.com/yhirose/cpp-httplib.git
  • 1

(2)添加cpp-httplib库和JSON库的头文件。将cpp-httplib存储库的include文件夹拷贝到项目文件夹中。确保项目结构如下所示:

——project_folder/
  ├─ cpp-httplib/
  │   └─ include/
  │       ├─ httplib.h
  │       └─ (其他cpp-httplib头文件)
  └─ your_files.cpp
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

注意:cpp-httplib库还需要JSON库来处理JSON数据。需要下载并添加JSON库。

(3)编写cpp-httplib代码。编写一个使用cpp-httplib库发送HTTP请求的示例代码(例如httplib_example.cpp)。

#include <iostream>
#include <httplib.h>

int main() {
    // 创建httplib客户端
    httplib::Client client("blog.csdn.net");

    // 发送GET请求
    auto response = client.Get("/Long_xu");

    // 检查响应
    if (response && response->status == 200) {
        std::cout << "Response body: " << response->body << std::endl;
    } else {
        std::cerr << "Failed to send HTTP request." << std::endl;
        return 1;
    }

    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

(4)编译和运行代码

g++ httplib_example.cpp -std=c++11 -o httplib_example
  • 1

运行生成的可执行文件:

./httplib_example
  • 1

五、自己实现socket发送 HTTP 请求

通过使用C++中的套接字(Socket)来发送HTTP请求的方式不具备第三方库或框架那样的功能和性能。

示例代码:

#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string>

int main() {
    // 创建套接字
    int socket_desc = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_desc == -1) {
        std::cerr << "Could not create socket." << std::endl;
        return 1;
    }

    // 设定服务器地址和端口
    std::string server = "192.168.1.101";
    int port = 80;
    
    // 解析服务器 IP 地址
    struct hostent* host = gethostbyname(server.c_str());
    if (host == nullptr) {
        std::cerr << "Could not resolve hostname." << std::endl;
        return 1;
    }
    struct in_addr address;
    memcpy(&address, host->h_addr_list[0], sizeof(struct in_addr));

    // 设置服务器地址结构
    struct sockaddr_in server_addr{};
    server_addr.sin_addr = address;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);

    // 连接服务器
    if (connect(socket_desc, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
        std::cerr << "Could not connect to server." << std::endl;
        return 1;
    }

    // 构建HTTP请求
    std::string request =
        "GET /endpoint HTTP/1.1\r\n"
        "Host: " + server + "\r\n"
        "User-Agent: C++ HTTP Client\r\n"
        "Connection: close\r\n\r\n";

    // 发送HTTP请求
    if (send(socket_desc, request.c_str(), request.length(), 0) < 0) {
        std::cerr << "Failed to send HTTP request." << std::endl;
        return 1;
    }

    // 接收并打印服务器响应
    std::string response;
    char buffer[4096];
    while (true) {
        memset(buffer, 0, sizeof(buffer));
        int bytes_received = recv(socket_desc, buffer, sizeof(buffer) - 1, 0);
        if (bytes_received <= 0) {
            break;
        }
        response += buffer;
    }

    std::cout << response << std::endl;

    // 关闭套接字
    close(socket_desc);

    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71

总结

  • 在使用Boost.Beast库发送HTTP请求时,步骤如下:

    1. 安装Boost库。
    2. 使用Boost.Beast库的代码发送HTTP请求。
  • 在使用cpp-httplib库发送HTTP请求时,步骤如下:

    1. 下载cpp-httplib库源代码。
    2. 添加cpp-httplib库和JSON库的头文件。
    3. 使用cpp-httplib库的代码发送HTTP请求。

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/685376
推荐阅读
相关标签
  

闽ICP备14008679号