Can't do https-request with boost beast
Asked Answered
T

1

6

Im using mingw64.

How can I make https-request using boost beast lib?

I got code below and it works, but I recieve answer: "400 The plain HTTP request was sent to HTTPS port"

What should I complete here to make https request? OpenSSL is installed.

#include <boost/beast/root_certificates.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl/error.hpp>
#include <boost/asio/ssl/stream.hpp>
#include <iostream>

void boost_request()
{
    namespace http = boost::beast::http;
    const std::string host = "api.vk.com"; //"scooterlabs.com";
    const std::string target = "/method/wall.get?&owner_id=-***&access_token=***&v=5.61&count=1000"; //"/echo?input=test";

    boost::asio::io_context ioc;
    boost::asio::ip::tcp::resolver resolver(ioc);
    boost::asio::ip::tcp::socket socket(ioc);
    boost::asio::ip::tcp::resolver::query query("api.vk.com", "https");
    boost::asio::connect(socket.lowest_layer(), resolver.resolve(query));
    socket.lowest_layer().set_option(boost::asio::ip::tcp::no_delay(true));
    http::request<http::string_body> req(http::verb::get, target, 11);
    req.set(http::field::host, host);
    req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
    http::write(socket, req);
    boost::beast::flat_buffer buffer;
    http::response<http::dynamic_body> res;
    http::read(socket, buffer, res);
    std::cout << res << std::endl;
    socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both);
}

int main()
{
    boost_request();
}
Tersina answered 10/3, 2019 at 18:29 Comment(1)
Please intend your code consistently and improve the phrasing of both code and text.Eweneck
E
5

Your stream type is asio::ip::tcp::socket. It needs to be asio::ssl::stream<asio::ip::tcp::socket>.

complete example in the documentation:

https://www.boost.org/doc/libs/1_69_0/libs/beast/example/http/client/sync-ssl/http_client_sync_ssl.cpp

Emotional answered 10/3, 2019 at 20:59 Comment(3)
Great answer for client, but do I need similar updates for server side?Typify
Yes. An ssl connection requires an ssl stream type.Emotional
There are examples in the beast documentationEmotional

© 2022 - 2024 — McMap. All rights reserved.