【发布时间】:2018-10-02 18:18:35
【问题描述】:
我尝试单独读取标题,但在使用任何主机时都会出错。
班级成员:
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的开发者提出的code也不起作用——同样的错误。
Boost 版本 1.68
我做错了吗?
编辑:
在示例中是一个错字。应该是:
std::string s =
"POST /cgi/message.php HTTP/1.1\r\n"
"Content-Length: 5\r\n"
"\r\n"
"abcde";
但是异步读取header的主要问题并没有解决。
【问题讨论】:
-
你没有指定错误的类型
-
@user3159253,错误的类型是什么?
-
> "我在使用任何主机时都会遇到错误" 错误是什么?类型、消息等?
-
@user3159253,
if(ec)-- 这是真的。ec.message()返回bad method。这就是我所知道的关于错误的全部信息。我找到了topic,我认为这与我的问题有关。
标签: c++ http asynchronous boost boost-beast