使用Boost Asio和OpenSSL创建HTTPS请求 [英] Creating a HTTPS request using Boost Asio and OpenSSL
问题描述
我创建了一个简单的HTTP请求,其中我正在向服务器发送GET,POST和PUT请求.接下来,我想使用boost asio库切换到HTTPS连接,我应该如何进行?
I have created a simple HTTP request wherein I am sending GET,POST and PUT requests to the server. Next I want to switch to HTTPS connection using boost asio library, how should I proceed?
我有一个Executor类来解析并连接到服务器,还有一个RequestCreator类来创建请求.
I have an Executor Class that resolves and connects to the server and a RequestCreator Class that creates the request.
推荐答案
我恰好在评论(...)中张贴了这样的内容:
I happen to just have posted such a thing in a comment (...):
您只需通过SSL连接即可. @Milind coliru.stacked-crooked.com/a/9546326fd1def416
所以也许对您有帮助.
#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(svc, ssl::context::method::sslv23_client);
ssl::stream<ip::tcp::socket> ssock(svc, ctx);
ssock.lowest_layer().connect({ {}, 8087 }); // http://localhost:8087 for test
ssock.handshake(ssl::stream_base::handshake_type::client);
// send request
std::string request("GET /newGame?name=david HTTP/1.1\r\n\r\n");
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";
}
为了演示目的仿真服务器,我一直在使用Asio示例中的证书和参数( https://stackoverflow. com/a/31201907/85371 ).
To emulate a server for demo purposes I've been using the certificate and params from the Asio samples (https://stackoverflow.com/a/31201907/85371).
更新,这是一个使用解析器解析端点的版本(Coliru不允许我们这样做,但它在非受限计算机上也可以使用).
UPDATE Here's a version that uses resolver to resolve the endpoint (Coliru doesn't allow us to do that, but it does work on non-restricted machines).
ip::tcp::resolver resolver(svc);
auto it = resolver.resolve({"localhost", "8087"}); // http://localhost:8087 for test
boost::asio::connect(ssock.lowest_layer(), it);
// and the rest unaltered
ssock.handshake(ssl::stream_base::handshake_type::client);
这篇关于使用Boost Asio和OpenSSL创建HTTPS请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!