C++使用HTTP庫和框架輕松發(fā)送HTTP請求
一、引言
使用C++編程發(fā)送HTTP請求通常需要使用第三方的HTTP庫或框架。在C++中,有幾個受歡迎的HTTP庫可供選擇,例如Curl、Boost.Beast和cpp-httplib。另外,也可以自己實現(xiàn)socket來發(fā)送http請求。
二、使用Curl庫發(fā)送HTTP請求
(1)安裝Curl庫。
對于Debian/Ubuntu系統(tǒng):
sudo apt-get install libcurl4-openssl-dev
對于RHEL/CentOS系統(tǒng):
sudo yum install libcurl-devel
對于macOS系統(tǒng):
brew install curl
(2)編寫Curl代碼。編寫一個C++代碼示例來使用Curl庫發(fā)送HTTP請求。將以下代碼保存為.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;
}
// 設置請求的URL
const char* url = "https://blog.csdn.net/Long_xu";
// 設置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;
}
(3)編譯和運行代碼。
g++ curl.cpp -lcurl -o example
然后,運行生成的可執(zhí)行文件:
./example
這里只是發(fā)送一個簡單的GET請求到指定的URL,并打印任何響應數(shù)據。可以根據需要對代碼進行修改和擴展,例如設置請求頭、發(fā)送POST請求、處理響應數(shù)據等。
三、使用Boost.Beast庫發(fā)送HTTP請求
(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);
// 解析主機名和端口
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);
// 連接到服務器
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, "/Long_xu", 11);
req.set(http::field::host, "blog.csdn.net");
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;
// 關閉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;
}
步驟 3: 編譯和運行代碼。
g++ beast_example.cpp -o beast_example -lboost_system -lboost_filesystem -lboost_thread -lboost_iostreams -lssl -lcrypto
運行生成的可執(zhí)行文件:
./beast_example
四、使用cpp-httplib庫發(fā)送HTTP請求
(1)下載cpp-httplib庫源代碼。要從cpp-httplib的GitHub倉庫下載庫的源代碼:
git clone https://github.com/yhirose/cpp-httplib.git
(2)添加cpp-httplib庫和JSON庫的頭文件。將cpp-httplib存儲庫的include文件夾拷貝到項目文件夾中。確保項目結構如下所示:
——project_folder/ ├─ cpp-httplib/ │ └─ include/ │ ├─ httplib.h │ └─ (其他cpp-httplib頭文件) └─ your_files.cpp
注意:cpp-httplib庫還需要JSON庫來處理JSON數(shù)據。需要下載并添加JSON庫。
(3)編寫cpp-httplib代碼。編寫一個使用cpp-httplib庫發(fā)送HTTP請求的示例代碼(例如httplib_example.cpp)。
#include <iostream>
#include <httplib.h>
int main() {
// 創(chuàng)建httplib客戶端
httplib::Client client("blog.csdn.net");
// 發(fā)送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;
}
(4)編譯和運行代碼。
g++ httplib_example.cpp -std=c++11 -o httplib_example
運行生成的可執(zhí)行文件:
./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;
}
// 設定服務器地址和端口
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";
// 發(fā)送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;
}
總結
在使用Boost.Beast庫發(fā)送HTTP請求時,步驟如下:
安裝Boost庫。
使用Boost.Beast庫的代碼發(fā)送HTTP請求。
在使用cpp-httplib庫發(fā)送HTTP請求時,步驟如下:
下載cpp-httplib庫源代碼。
添加cpp-httplib庫和JSON庫的頭文件。
使用cpp-httplib庫的代碼發(fā)送HTTP請求。
到此這篇關于C++使用HTTP庫和框架輕松發(fā)送HTTP請求的文章就介紹到這了,更多相關C++發(fā)送HTTP請求內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C++實現(xiàn)LeetCode(103.二叉樹的之字形層序遍歷)
這篇文章主要介紹了C++實現(xiàn)LeetCode(103.二叉樹的之字形層序遍歷),本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下2021-07-07
C++面向對象之類和對象那些你不知道的細節(jié)原理詳解
C++是面向對象編程的,這也是C++與C語言的最大區(qū)別,下面這篇文章主要給大家介紹了關于C++面向對象之類和對象的細節(jié)原理的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-05-05

