C++中發(fā)送HTTP請求的實現(xiàn)方式
一、簡介
使用C++編程發(fā)送HTTP請求通常需要使用第三方的HTTP庫或框架。在C++中,有幾個受歡迎的HTTP庫可供選擇,例如Curl、Boost.Beast和cpp-httplib。另外,也可以自己實現(xiàn)socket來發(fā)送http請求
二、使用Curl庫發(fā)送HTTP請求
1. 確認當前系統(tǒng)是什么系統(tǒng)
查看版本信息
cat /etc/os-release
2.linux環(huán)境中如何確認是否安裝過libcurl
1> 使用dpkg
(適用于Debian/Ubuntu系統(tǒng)):
dpkg -l | grep libcurl
2> 使用rpm(適用于Red Hat/CentOS系統(tǒng)):
rpm -qa | grep libcurl
3> 使用yum
(適用于CentOS/Red Hat系統(tǒng),用于檢查是否安裝,不顯示版本):
yum list installed | grep libcurl
4> 使用apt-get
(適用于Debian/Ubuntu系統(tǒng),用于檢查是否安裝,不顯示版本):
apt-get install libcurl
我使用的是yum方法
3.安裝Curl庫
a> 對于Debian/Ubuntu系統(tǒng):
sudo apt-get install libcurl4-openssl-dev
b> 對于RHEL/CentOS系統(tǒng):
sudo yum install libcurl-devel
c> 對于macOS系統(tǒng):
brew install curl
使用yum安裝
4.編寫Curl代碼
編寫一個C++代碼示例來使用Curl庫發(fā)送HTTP請求。將以下代碼保存為.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è)置請求的URL const char* url = "https://www.test.com"; // 設(shè)置Curl句柄的URL選項 curl_easy_setopt(curl, CURLOPT_URL, url); // 發(fā)送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; }
5.編譯
g++ curl.cpp -lcurl -o example
這里只是發(fā)送一個簡單的GET請求到指定的URL,并打印任何響應數(shù)據(jù)??梢愿鶕?jù)需要對代碼進行修改和擴展,例如設(shè)置請求頭、發(fā)送POST請求、處理響應數(shù)據(jù)等。
三、編寫B(tài)oost.Beast代碼
這里暫時不做boost庫安裝的介紹
簡單的使用,如下:
#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); // 解析主機名和端口 boost::asio::ip::tcp::resolver::results_type endpoints = resolver.resolve("www.test.com", "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請求 http::request<http::string_body> req(http::verb::get, "/Login", 11); req.set(http::field::host, "www.test.com"); req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING); // 發(fā)送HTTP請求 http::write(stream, req); // 接收HTTP響應 boost::beast::flat_buffer buffer; http::response<http::dynamic_body> res; http::read(stream, buffer, res); // 打印響應狀態(tài)碼和響應體 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); // 如果有錯誤,打印錯誤信息 if (ec && ec != boost::asio::error::eof) { std::cerr << "Error: " << ec.message() << std::endl; return 1; } return 0; }
編譯:
g++ beast_example.cpp -o beast_example -lboost_system -lboost_filesystem -lboost_thread -lboost_iostreams -lssl -lcrypto
四、使用cpp-httplib庫發(fā)送HTTP請求
下載cpp-httplib庫源代碼。要從cpp-httplib的GitHub倉庫下載庫的源代碼:
源碼庫地址:https://github.com/yhirose/cpp-httplib
編寫cpp-httplib代碼。編寫一個使用cpp-httplib庫發(fā)送HTTP請求的示例代碼:
#include <iostream> #include <httplib.h> int main() { // 創(chuàng)建httplib客戶端 httplib::Client client("www.test.com"); // 發(fā)送GET請求 auto response = client.Get("/Login"); // 檢查響應 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; }
編譯:
g++ httplib_example.cpp -std=c++11 -o httplib_example
五、自己實現(xiàn)socket發(fā)送 HTTP 請求
通過使用C++中的套接字(Socket)來發(fā)送HTTP請求的方式不具備第三方庫或框架那樣的功能和性能。
代碼示例:
#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請求 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請求 if (send(socket_desc, request.c_str(), request.length(), 0) < 0) { std::cerr << "Failed to send HTTP request." << std::endl; return 1; } // 接收并打印服務(wù)器響應 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; }
以上就是C++中發(fā)送HTTP請求的實現(xiàn)方式的詳細內(nèi)容,更多關(guān)于C++發(fā)送HTTP請求的資料請關(guān)注腳本之家其它相關(guān)文章!