当您重定向时,您不能只是“替换”现有请求上的位置。您甚至不能使用同一个套接字,除非在极少数情况下重定向目标位于同一个 TCP 端点上。
因为主机名、协议和路径可能已更改,您必须解析位置,获取方案、主机、路径部分。然后您必须再次进行正确的主机解析,并确保在Host
标头中使用正确的主机名。
这是一个示例,显示在“错误”的 url 处请求 Boost 许可证,该 urlhttp://boost.org/user/license.html
将立即重定向到http://www.boost.org/user/license.html
.
注意我曾经network::uri
为我们做 URI 解析:https ://github.com/reBass/uri
演示
#include <iostream>
#include <boost/beast.hpp>
#include <boost/beast/http.hpp>
#include <network/uri.hpp>
#include <boost/asio.hpp>
#include <string>
using boost::asio::ip::tcp;
namespace http = boost::beast::http;
struct Requester {
void do_request(std::string const& url) {
network::uri u{url};
auto const lookup = resolver_.resolve( tcp::resolver::query(u.host().to_string(), u.scheme().to_string()) );
// Set up an HTTP GET request message
tcp::socket socket{ios};
boost::asio::connect(socket, lookup);
http::request<http::string_body> req{http::verb::get, u.path().to_string(), 11};
req.keep_alive(true);
req.set(http::field::host, u.host().to_string());
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
std::cout << "Target: " << url << "\n";
std::cout << req << "\n";
http::write(socket, req);
boost::beast::flat_buffer buffer;
http::response<http::dynamic_body> res;
http::read(socket, buffer, res);
switch(res.base().result_int()) {
case 301:
std::cout << "Redirecting.....\n";
do_request(res.base()["Location"].to_string());
break;
case 200:
std::cout << res << "\n";
break;
default:
std::cout << "Unexpected HTTP status " << res.result_int() << "\n";
break;
}
}
private:
boost::asio::io_service ios;
tcp::resolver resolver_{ios};
};
int main() {
try {
Requester requester;
requester.do_request("http://boost.org/users/license.html"); // redirects to http://www.boost.org/...
} catch(std::exception const& e) {
std::cerr << "Exception: " << e.what() << "\n";
}
}
这打印:
Target: http://boost.org/users/license.html
GET /users/license.html HTTP/1.1
Host: boost.org
User-Agent: Boost.Beast/109
Redirecting.....
Target: http://www.boost.org/users/license.html
GET /users/license.html HTTP/1.1
Host: www.boost.org
User-Agent: Boost.Beast/109
HTTP/1.1 200 OK
Date: Sun, 27 Aug 2017 22:25:20 GMT
Server: Apache/2.2.15 (CentOS)
Accept-Ranges: bytes
Connection: close
Transfer-Encoding: chunked
Content-Type: text/html
90fd
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Boost Software License</title>
<meta http-equiv="Content-Type" content="text/html; charset=us-ascii" />
<link rel="icon" href="/favicon.ico" type="image/ico" />
<link rel="stylesheet" type="text/css" href="../style-v2/section-boost.css" />
<!--[if IE 7]> <style type="text/css"> body { behavior: url(/style-v2/csshover3.htc); } </style> <![endif]-->
</head><!--
Note: Editing website content is documented at:
http://www.boost.org/development/website_updating.html
-->
<body>
ENTIRE LICENSE BODY SNIPPED
</body>
</html>
0