用c++ 写一个http异步post 请求
以下是一个使用C++的Boost库编写的异步POST请求示例:
#include
using namespace boost::asio;
class HttpClient { public: HttpClient(io_service& io, const std::string& host, const std::string& path) : host_(host), path_(path), resolver_(io), socket_(io) {}
void post(const std::string& data) {
// 异步解析主机名和服务
tcp::resolver::query query(host_, "http");
resolver_.async_resolve(query,
boost::bind(&HttpClient::handle_resolve, this,
boost::asio::placeholders::error,
boost::asio::placeholders::iterator,
data));
}
private: void handle_resolve(const boost::system::error_code& ec, tcp::resolver::iterator iterator, const std::string& data) { if (!ec) { // 异步连接 async_connect(socket_, iterator, boost::bind(&HttpClient::handle_connect, this, boost::asio::placeholders::error, data)); } else { std::cout << "resolve error: " << ec.message() << std::endl; } }
void handle_connect(const boost::system::error_code& ec, const std::string& data) {
if (!ec) {
// 构造HTTP POST请求头和消息体
std::string request = "POST " + path_ + " HTTP/1.1\r\n"
+ "Host: " + host_ + "\r\n"
+ "Content-Type: application/x-www-form-urlencoded\r\n"
+ "Content-Length: " + std::to_string(data.size()) + "\r\n"
+ "Connection: close\r\n\r\n"
+ data;
// 异步发送HTTP POST请求
async_write(socket_, buffer(request),
boost::bind(&HttpClient::handle_write, this,
boost::asio::placeholders::error));
}
else {
std::cout << "connect error: " << ec.message() << std::endl;
}
}
void handle_write(const boost::system::error_code& ec) {
if (!ec) {
// 异步读取响应
async_read(socket_, buffer(response_),
boost::bind(&HttpClient::handle_read, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
else {
std::cout << "write error: " << ec.message() << std::endl;
}
}
void handle_read(const boost::system::error_code& ec, std::size_t bytes_transferred) {
if (!ec) {
// 输出响应
std::cout << response_.data() << std::endl;
}
else {
std::cout << "read error: " << ec.message() << std::endl;
}
}
private: std::string host_; std::string path_; tcp::resolver resolver_; tcp::socket socket_; boost::asio::streambuf response_; };
int main() { io_service io; HttpClient client(io, "www.example.com", "/post"); client.post("key1=value1&key2=value2"); io.run(); return 0; }
注意,该示例仅供参考,实际使用时需要根据具体情况进行修改和调试
原文地址: https://www.cveoy.top/t/topic/hmQt 著作权归作者所有。请勿转载和采集!