我正在尝试将boost beast http库用于HTTP客户端。当我使用模拟服务器时,它可以正常工作,但是当我尝试连接到真实服务器时,boost::beast::http::read抛出一个异常,说“部分消息”。
我已经在这个问题上工作了几天了,但是我不知道为什么。到目前为止,我一直在使用一个不同的http客户端库,服务器的通信工作正常,没有任何类似的问题。
对于为什么会发生这种情况,以及为什么在使用不同的库时,这似乎不是问题,我将非常感谢任何类型的想法或提示。
发布于 2021-02-11 00:57:15
boost::beast::http::read抛出一个异常,说是“部分消息”。
发生这种情况是因为正在解析的消息不完整。一个典型的原因是content-length报头错误,或者发送者过早地放弃了连接。例如:
这就是http::[async_]read最终在幕后做的事情,但没有网络相关的东西:
#include <iostream>
#include <iomanip>
#include <string_view>
#include <boost/beast/http.hpp>
int main() {
using namespace boost::beast::http;
using boost::asio::buffer;
for (std::string_view buf : {
"GET / HTTP/1.1\r\n", // incomplete headers
"GET / HTTP/1.1\r\nHost: example.com\r\nContent-Length: 0\r\n\r\ntrailing data",
"GET / HTTP/1.1\r\nHost: example.com\r\nContent-Length: 42\r\n\r\nshort",
})
{
//std::cout << std::quoted(test) << "\n";
std::cout << "---------------------" << "\n";
request_parser<string_body> parser;
boost::system::error_code ec;
size_t n = parser.put(buffer(buf), ec);
if (n && !ec && !parser.is_done()) {
buf.remove_prefix(n);
n = parser.put(buffer(buf), ec); // body
}
if (!ec)
parser.put_eof(ec);
buf.remove_prefix(n);
std::cout
<< (parser.is_header_done()?"headers ok":"incomplete headers")
<< " / " << (parser.is_done()?"done":"not done")
<< " / " << ec.message() << "\n";
if (parser.is_header_done() && !parser.is_done())
std::cout << parser.content_length_remaining().value_or(0) << " more content bytes expected\n";
if (!buf.empty())
std::cout << "Remaining buffer: " << std::quoted(buf) << "\n";
}
}打印
---------------------
incomplete headers / not done / need more
---------------------
headers ok / done / Success
Remaining buffer: "trailing data"
---------------------
headers ok / not done / partial message
37 more content bytes expected如果您没有将error_code传递给您的调用,它们将抛出带有相同代码的异常system_error,这正是您所看到的。
附注
如果另一个库没有这个“问题”,有两个选择:
https://stackoverflow.com/questions/66140059
复制相似问题