Answer the question
In order to leave comments, you need to log in
How to make a simple get request using boost?
I'm interested in creating a program that simply sends a get request like
example.com/api.php?input=test over the http protocol and that's it, you don't need to get a response or do anything else. Everything is simple. I will be very happy if there is a working code and with an explanation.
And specifically on so ahri9fox.online/apiapp.php?input=a
Answer the question
In order to leave comments, you need to log in
An example using Boost.Beast (available since version 1.66). Based on the example from here and slightly modified it.
#include <boost/beast.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
namespace http = boost::beast::http;
int main() {
const std::string host = "scooterlabs.com";
const std::string target = "/echo?input=test";
// I/O контекст, необходимый для всех I/O операций
boost::asio::io_context ioc;
// Resolver для определения endpoint'ов
boost::asio::ip::tcp::resolver resolver(ioc);
// Tcp сокет, использующейся для соединения
boost::asio::ip::tcp::socket socket(ioc);
// Резолвим адрес и устанавливаем соединение
boost::asio::connect(socket, resolver.resolve(host, "80"));
// Дальше необходимо создать HTTP GET реквест с указанием таргета
http::request<http::string_body> req(http::verb::get, target, 11);
// Задаём поля HTTP заголовка
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);
return 0;
}
g++ -lboost_system -pthread main.cpp
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question