我尝试单独读取标题,但在使用任何主机时都会出错。
班级成员:
boost::asio::io_context ioc_;
// The SSL context is required, and holds certificates
boost::asio::ssl::context ctx_{boost::asio::ssl::context::sslv23_client};
boost::asio::ssl::stream<boost::asio::ip::tcp::socket> stream_{ioc_, ctx_}; // https
boost::asio::ip::tcp::socket socket_{ioc_}; // http
boost::beast::http::request_parser<boost::beast::http::string_body> header_parser_;
boost::asio::streambuf strbuf_;
方法:
void AsyncHttpClient::onWrite(boost::system::error_code ec, std::size_t bytes_transferred)
{
boost::ignore_unused(bytes_transferred);
if(ec)
return fail(ec, "write");
if (https_mode_) {
boost::beast::http::async_read_header(socket_, strbuf_, header_parser_, std::bind(&AsyncHttpClient::onReadHeader, this, std::placeholders::_1, std::placeholders::_2));
}
else {
// Receive the HTTP response
boost::beast::http::async_read_header(socket_, strbuf_, header_parser_, std::bind(&AsyncHttpClient::onReadHeader, this, std::placeholders::_1, std::placeholders::_2));
}
}
void AsyncHttpClient::onReadHeader(boost::system::error_code ec, std::size_t bytes_transferred)
{
boost::ignore_unused(bytes_transferred);
std::cout << bytes_transferred << std::endl;
if(ec)
return fail(ec, "read header"); // Here is the error `bad method`
std::string header_{boost::asio::buffers_begin(strbuf_.data()), boost::asio::buffers_begin(strbuf_.data()) + static_cast<signed long>(bytes_transferred)};
std::cout << header_ << std::endl;
std::string s =
"HTTP/1.1 200 OK\r\n"
"Content-Length: 5\r\n"
"\r\n"
"*****";
boost::beast::error_code ec_;
boost::beast::http::request_parser<boost::beast::http::string_body> p;
p.put(boost::asio::buffer(s), ec_);
if (ec_) {
return fail(ec_, "parse header"); // Here is the error `bad method`
}
}
fail
的代码:
void AsyncHttpClient::fail(boost::system::error_code ec, const char *what)
{
std::cerr << what << ": " << ec.message() << "\n";
}
响应头:
HTTP/1.0 200 OK
Server: SimpleHTTP/0.6 Python/3.6.6
Date: Wed, 03 Oct 2018 13:02:12 GMT
Content-type: text/x-c++src
Content-Length: 205
Last-Modified: Mon, 17 Sep 2018 14:04:14 GMT
此外,Boost.Beast 的开发者提出的代码不起作用——同样的错误。
提升版本 1.68
难道我做错了什么?
编辑:
在示例中是一个错字。它应该是:
std::string s =
"POST /cgi/message.php HTTP/1.1\r\n"
"Content-Length: 5\r\n"
"\r\n"
"abcde";
但是异步读取头的主要问题并没有解决。