C++中發(fā)送HTTP請(qǐng)求的實(shí)現(xiàn)方式
一、簡(jiǎn)介
使用C++編程發(fā)送HTTP請(qǐng)求通常需要使用第三方的HTTP庫(kù)或框架。在C++中,有幾個(gè)受歡迎的HTTP庫(kù)可供選擇,例如Curl、Boost.Beast和cpp-httplib。另外,也可以自己實(shí)現(xiàn)socket來(lái)發(fā)送http請(qǐng)求
二、使用Curl庫(kù)發(fā)送HTTP請(qǐng)求
1. 確認(rèn)當(dāng)前系統(tǒng)是什么系統(tǒng)
查看版本信息
cat /etc/os-release

2.linux環(huán)境中如何確認(rèn)是否安裝過(guò)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庫(kù)
a> 對(duì)于Debian/Ubuntu系統(tǒng):
sudo apt-get install libcurl4-openssl-dev
b> 對(duì)于RHEL/CentOS系統(tǒng):
sudo yum install libcurl-devel
c> 對(duì)于macOS系統(tǒng):
brew install curl
使用yum安裝

4.編寫(xiě)Curl代碼
編寫(xiě)一個(gè)C++代碼示例來(lái)使用Curl庫(kù)發(fā)送HTTP請(qǐng)求。將以下代碼保存為.cpp文件
#include <iostream>
#include <curl/curl.h>
int main()
{
// 初始化Curl庫(kù)
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://www.test.com";
// 設(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庫(kù)
curl_easy_cleanup(curl);
curl_global_cleanup();
return 0;
}5.編譯
g++ curl.cpp -lcurl -o 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ù)等。
三、編寫(xiě)B(tài)oost.Beast代碼
這里暫時(shí)不做boost庫(kù)安裝的介紹
簡(jiǎn)單的使用,如下:
#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("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請(qǐng)求
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請(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;
}編譯:
g++ beast_example.cpp -o beast_example -lboost_system -lboost_filesystem -lboost_thread -lboost_iostreams -lssl -lcrypto
四、使用cpp-httplib庫(kù)發(fā)送HTTP請(qǐng)求
下載cpp-httplib庫(kù)源代碼。要從cpp-httplib的GitHub倉(cāng)庫(kù)下載庫(kù)的源代碼:
源碼庫(kù)地址:https://github.com/yhirose/cpp-httplib
編寫(xiě)cpp-httplib代碼。編寫(xiě)一個(gè)使用cpp-httplib庫(kù)發(fā)送HTTP請(qǐng)求的示例代碼:
#include <iostream>
#include <httplib.h>
int main() {
// 創(chuàng)建httplib客戶(hù)端
httplib::Client client("www.test.com");
// 發(fā)送GET請(qǐng)求
auto response = client.Get("/Login");
// 檢查響應(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;
}編譯:
g++ httplib_example.cpp -std=c++11 -o httplib_example
五、自己實(shí)現(xiàn)socket發(fā)送 HTTP 請(qǐng)求
通過(guò)使用C++中的套接字(Socket)來(lái)發(fā)送HTTP請(qǐng)求的方式不具備第三方庫(kù)或框架那樣的功能和性能。
代碼示例:
#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;
}以上就是C++中發(fā)送HTTP請(qǐng)求的實(shí)現(xiàn)方式的詳細(xì)內(nèi)容,更多關(guān)于C++發(fā)送HTTP請(qǐng)求的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
c++11 chrono全面解析(最高可達(dá)納秒級(jí)別的精度)
chrono是c++ 11中的時(shí)間庫(kù),本文就來(lái)詳細(xì)的介紹一下chrono庫(kù)的具體使用,關(guān)鍵是理解里面時(shí)間段(Durations)、時(shí)間點(diǎn)(Time points)的概念,感興趣的可以了解一下2021-11-11
如何寫(xiě)好C main函數(shù)的幾個(gè)注意事項(xiàng)
這篇文章主要介紹了如何寫(xiě)好C main函數(shù)的幾個(gè)注意事項(xiàng),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06
Qt項(xiàng)目無(wú)法找到.pro文件的解決方案匯總
在使用Qt Creator開(kāi)發(fā)過(guò)程中,遇到"Cannot find file: [項(xiàng)目路徑].pro"的錯(cuò)誤提示,錯(cuò)誤通常發(fā)生在項(xiàng)目打開(kāi)、構(gòu)建或部署時(shí),導(dǎo)致開(kāi)發(fā)流程中斷,本文將從多個(gè)角度分析問(wèn)題原因并提供系統(tǒng)的解決方案,需要的朋友可以參考下2025-10-10
C語(yǔ)言關(guān)于include順序不同導(dǎo)致編譯結(jié)果不同的問(wèn)題
這篇文章主要介紹了在日常調(diào)試C語(yǔ)言中include的順序不同從而影響最后編譯結(jié)果不同的問(wèn)題,究其原因是寫(xiě)代碼的習(xí)慣所導(dǎo)致,下面跟小編一起來(lái)看看吧2022-04-04

