C++使用HTTP庫和框架輕松發(fā)送HTTP請(qǐng)求
一、引言
使用C++編程發(fā)送HTTP請(qǐng)求通常需要使用第三方的HTTP庫或框架。在C++中,有幾個(gè)受歡迎的HTTP庫可供選擇,例如Curl、Boost.Beast和cpp-httplib。另外,也可以自己實(shí)現(xiàn)socket來發(fā)送http請(qǐng)求。
二、使用Curl庫發(fā)送HTTP請(qǐng)求
(1)安裝Curl庫。
對(duì)于Debian/Ubuntu系統(tǒng):
sudo apt-get install libcurl4-openssl-dev
對(duì)于RHEL/CentOS系統(tǒng):
sudo yum install libcurl-devel
對(duì)于macOS系統(tǒng):
brew install curl
(2)編寫Curl代碼。編寫一個(gè)C++代碼示例來使用Curl庫發(fā)送HTTP請(qǐng)求。將以下代碼保存為.cpp
文件(例如curl.cpp
)。
#include <iostream> #include <curl/curl.h> int main() { // 初始化Curl庫 curl_global_init(CURL_GLOBAL_ALL); // 創(chuàng)建Curl句柄 CURL* curl = curl_easy_init(); if (!curl) { std::cerr << "Failed to initialize Curl." << std::endl; return 1; } // 設(shè)置請(qǐng)求的URL const char* url = "https://blog.csdn.net/Long_xu"; // 設(shè)置Curl句柄的URL選項(xiàng) curl_easy_setopt(curl, CURLOPT_URL, url); // 發(fā)送GET請(qǐng)求 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; }
(3)編譯和運(yùn)行代碼。
g++ curl.cpp -lcurl -o example
然后,運(yùn)行生成的可執(zhí)行文件:
./example
這里只是發(fā)送一個(gè)簡(jiǎn)單的GET請(qǐng)求到指定的URL,并打印任何響應(yīng)數(shù)據(jù)。可以根據(jù)需要對(duì)代碼進(jìn)行修改和擴(kuò)展,例如設(shè)置請(qǐng)求頭、發(fā)送POST請(qǐng)求、處理響應(yīng)數(shù)據(jù)等。
三、使用Boost.Beast庫發(fā)送HTTP請(qǐng)求
(1)安裝Boost庫。前面有文章介紹了Boost庫的安裝,這里就不再贅述。
(2)編寫B(tài)oost.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() { // 創(chuàng)建Boost.Beast I/O上下文 boost::asio::io_context ioc; // 創(chuàng)建TCP解析器 boost::asio::ip::tcp::resolver resolver(ioc); // 解析主機(jī)名和端口 boost::asio::ip::tcp::resolver::results_type endpoints = resolver.resolve("blog.csdn.net", "https"); // 創(chuàng)建SSL上下文 boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23); // SSL連接 boost::beast::ssl_stream<boost::asio::ip::tcp::socket> stream(ioc, ctx); // 連接到服務(wù)器 boost::asio::connect(stream.next_layer(), endpoints.begin(), endpoints.end()); // SSL握手 stream.handshake(boost::asio::ssl::stream_base::client); // 創(chuàng)建HTTP請(qǐng)求 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); // 發(fā)送HTTP請(qǐng)求 http::write(stream, req); // 接收HTTP響應(yīng) boost::beast::flat_buffer buffer; http::response<http::dynamic_body> res; http::read(stream, buffer, res); // 打印響應(yīng)狀態(tài)碼和響應(yīng)體 std::cout << "Response code: " << res.result_int() << std::endl; std::cout << "Response body: " << boost::beast::buffers_to_string(res.body().data()) << std::endl; // 關(guān)閉SSL連接 boost::beast::error_code ec; stream.shutdown(ec); // 如果有錯(cuò)誤,打印錯(cuò)誤信息 if (ec && ec != boost::asio::error::eof) { std::cerr << "Error: " << ec.message() << std::endl; return 1; } return 0; }
步驟 3: 編譯和運(yùn)行代碼。
g++ beast_example.cpp -o beast_example -lboost_system -lboost_filesystem -lboost_thread -lboost_iostreams -lssl -lcrypto
運(yùn)行生成的可執(zhí)行文件:
./beast_example
四、使用cpp-httplib庫發(fā)送HTTP請(qǐng)求
(1)下載cpp-httplib庫源代碼。要從cpp-httplib的GitHub倉庫下載庫的源代碼:
git clone https://github.com/yhirose/cpp-httplib.git
(2)添加cpp-httplib庫和JSON庫的頭文件。將cpp-httplib存儲(chǔ)庫的include文件夾拷貝到項(xiàng)目文件夾中。確保項(xiàng)目結(jié)構(gòu)如下所示:
——project_folder/ ├─ cpp-httplib/ │ └─ include/ │ ├─ httplib.h │ └─ (其他cpp-httplib頭文件) └─ your_files.cpp
注意:cpp-httplib庫還需要JSON庫來處理JSON數(shù)據(jù)。需要下載并添加JSON庫。
(3)編寫cpp-httplib代碼。編寫一個(gè)使用cpp-httplib庫發(fā)送HTTP請(qǐng)求的示例代碼(例如httplib_example.cpp
)。
#include <iostream> #include <httplib.h> int main() { // 創(chuàng)建httplib客戶端 httplib::Client client("blog.csdn.net"); // 發(fā)送GET請(qǐng)求 auto response = client.Get("/Long_xu"); // 檢查響應(yīng) 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; }
(4)編譯和運(yùn)行代碼。
g++ httplib_example.cpp -std=c++11 -o httplib_example
運(yùn)行生成的可執(zhí)行文件:
./httplib_example
五、自己實(shí)現(xiàn)socket發(fā)送 HTTP 請(qǐng)求
通過使用C++中的套接字(Socket)來發(fā)送HTTP請(qǐng)求的方式不具備第三方庫或框架那樣的功能和性能。
示例代碼:
#include <iostream> #include <sys/socket.h> #include <arpa/inet.h> #include <netdb.h> #include <string> int main() { // 創(chuàng)建套接字 int socket_desc = socket(AF_INET, SOCK_STREAM, 0); if (socket_desc == -1) { std::cerr << "Could not create socket." << std::endl; return 1; } // 設(shè)定服務(wù)器地址和端口 std::string server = "192.168.1.101"; int port = 80; // 解析服務(wù)器 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)); // 設(shè)置服務(wù)器地址結(jié)構(gòu) struct sockaddr_in server_addr{}; server_addr.sin_addr = address; server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port); // 連接服務(wù)器 if (connect(socket_desc, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) { std::cerr << "Could not connect to server." << std::endl; return 1; } // 構(gòu)建HTTP請(qǐng)求 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"; // 發(fā)送HTTP請(qǐng)求 if (send(socket_desc, request.c_str(), request.length(), 0) < 0) { std::cerr << "Failed to send HTTP request." << std::endl; return 1; } // 接收并打印服務(wù)器響應(yīng) 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; // 關(guān)閉套接字 close(socket_desc); return 0; }
總結(jié)
在使用Boost.Beast庫發(fā)送HTTP請(qǐng)求時(shí),步驟如下:
安裝Boost庫。
使用Boost.Beast庫的代碼發(fā)送HTTP請(qǐng)求。
在使用cpp-httplib庫發(fā)送HTTP請(qǐng)求時(shí),步驟如下:
下載cpp-httplib庫源代碼。
添加cpp-httplib庫和JSON庫的頭文件。
使用cpp-httplib庫的代碼發(fā)送HTTP請(qǐng)求。
到此這篇關(guān)于C++使用HTTP庫和框架輕松發(fā)送HTTP請(qǐng)求的文章就介紹到這了,更多相關(guān)C++發(fā)送HTTP請(qǐng)求內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語言實(shí)現(xiàn)的順序表功能完整實(shí)例
這篇文章主要介紹了C語言實(shí)現(xiàn)的順序表功能,結(jié)合完整實(shí)例形式分析了C語言順序表的創(chuàng)建、添加、刪除、排序、合并等相關(guān)操作技巧,需要的朋友可以參考下2018-04-04C++內(nèi)存泄漏檢測(cè)和解決方法小結(jié)
內(nèi)存泄露在編程中是常見的一種問題,一但程序發(fā)生內(nèi)存泄露問題,將導(dǎo)致程序崩潰無法運(yùn)行,內(nèi)存泄漏是指程序在運(yùn)行過程中,由于疏忽或錯(cuò)誤導(dǎo)致已分配的內(nèi)存空間無法被正確釋放,本文給大家就介紹了C++中內(nèi)存泄漏如何檢測(cè)和解決,需要的朋友可以參考下2025-01-01C++實(shí)現(xiàn)LeetCode(103.二叉樹的之字形層序遍歷)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(103.二叉樹的之字形層序遍歷),本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07C語言實(shí)現(xiàn)三子棋簡(jiǎn)單小游戲
這篇文章主要為大家詳細(xì)介紹了C語言實(shí)現(xiàn)三子棋簡(jiǎn)單小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09C++面向?qū)ο笾惡蛯?duì)象那些你不知道的細(xì)節(jié)原理詳解
C++是面向?qū)ο缶幊痰?這也是C++與C語言的最大區(qū)別,下面這篇文章主要給大家介紹了關(guān)于C++面向?qū)ο笾惡蛯?duì)象的細(xì)節(jié)原理的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-05-05