为什么Boost.Asio SSL请求返回405不允许



我正试图通过以下代码向服务器发送HTTPS请求并接收页面内容:

#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <iostream>
int main() {
boost::system::error_code ec;
using namespace boost::asio;
// what we need
io_service svc;
ssl::context ctx(ssl::context::method::tlsv1);
ssl::stream<ip::tcp::socket> ssock(svc, ctx);
ip::tcp::endpoint endpoint(boost::asio::ip::make_address("157.90.94.153",ec),443);
ssock.lowest_layer().connect(endpoint); 
ssock.handshake(ssl::stream_base::handshake_type::client);
// send request
std::string request("GET /index.html HTTP/1.1rnrn");
boost::asio::write(ssock, buffer(request));
// read response
std::string response;
do {
char buf[1024];
size_t bytes_transferred = ssock.read_some(buffer(buf), ec);
if (!ec) response.append(buf, buf + bytes_transferred);
} while (!ec);
// print and exit
std::cout << "Response received: '" << response << "'n";
}

但我在本地电脑上不断收到405不允许,在Coliru上收到400错误请求

我做错了什么?

... "GET /index.html HTTP/1.1rnrn"

这不是一个有效的HTTP/1.1请求。它必须至少还包含一个Host字段,并且该字段的值必须与服务器的期望值相匹配,即

"GET /index.html HTTP/1.1rnHost: example.comrnrn"

一般来说,HTTP看起来可能很简单,但实际上很复杂,并且有几个陷阱。如果你真的需要自己做HTTP,请研究一下标准。

最新更新