下雪了

【Boost】发送/接收HTML请求(Get/Post)

头文件:

#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <boost/locale.hpp>

具体步骤:

void conn()
{

    try
    {
        //三个基础参数
        string host="zofz.cf";
        string port="80";
        string target="/123/";

        //http版本
        int version = 11;

        //建立基础IO接口,并初始化resolver和socket
        boost::asio::io_service io_se;
        boost::asio::ip::tcp::resolver resolver{ io_se };
        boost::asio::ip::tcp::socket socket{ io_se };

        //设定GET/POST请求
        boost::asio::streambuf request;
        std::ostream request_stream(&request);

        //创建http头,注意格式
        request_stream << "GET " << target << " HTTP/1.1 \r\n";
        request_stream << "Host: " << host << "\r\n";
        request_stream << "Accept: application/json \r\n";
        request_stream << "Accept-Encoding: gzip, deflate, br \r\n";
        request_stream << "Conection: keep-alive \r\n";
        request_stream << "Content-Type: application/x-www-form-urlencoded \r\n";
        request_stream << "User-Agent: " << ua << " \r\n";

        // 发送request
        write(socket, request);

        //声明一个容器来保存响应
        boost::beast::flat_buffer buf;
        response<string_body> resp;
        stringstream ss;

        //接收容器
        read(socket, buf, resp);
        
        //遍历Header
        for(auto &i:resp)
        {
            cout<<i.name()<<i.value()<<endl;
        }
        
        //输出body
        cout<<resp.body()<<endl;
    }
    catch (std::exception const& e)
    {
        //输出错误
        cout<< e.what()<<);
    }
}

 


Add Your Comment

* Indicates Required Field

Your email address will not be published.

*