使boost http客户端

Make boost http client

本文关键字:客户端 http boost      更新时间:2023-10-16

我是boost库的新手,所以我的问题可能不是这个论坛的第一个问题,但我找不到类似的情况。目前,我正试图实现一个简单的HTTP客户端调用REST API。我从boost网站上给出的例子中获得灵感:带有boost的HTTP客户端

这个例子对于像我这样的新手来说是足够清楚的,但我想让客户端能够一个接一个地执行多个请求,因为这个例子是一次性的:客户端向服务器发送一个GET请求,然后接收响应,之后io_service.run()返回。

所以我的问题是我需要从boost中使用什么方式来使我的客户端总是等待新的请求发送。

我读了一些关于io_service::工作,但我不确定它是否是正确的方式。

有没有人做过类似于我想要做的客户端?提前感谢!

敬上,

安东

我不知道异步版本是否必须,所以我建议您尝试同步版本,因为它更容易遵循执行路径:

/*
Compile with
    g++ -lpthread -lboost_system -lboost_thread -ohttp http.cpp
*/
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <boost/asio.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread/thread.hpp> 

using std::cout;
using std::endl;
using std::vector;
using std::string;
using boost::asio::ip::tcp;
using boost::asio::ip::address;
using boost::asio::io_service;
using boost::asio::buffer;
using boost::system::error_code;
using boost::system::system_error;

int main()
{
    try
    {
        unsigned int PORT = 80;
        const string HOST = "216.58.214.238";
        const string HTTP_REQUEST = "GET /index.html HTTP/1.0nn";
        io_service ios;
        tcp::endpoint ip_port(address::from_string(HOST), PORT);
        while (true)
        {
            tcp::socket client(ios);
            client.connect(ip_port);
            const int BUFLEN = 1024;
            vector<char> buf(BUFLEN);
            client.send(buffer(HTTP_REQUEST, HTTP_REQUEST.size()));
            error_code error;
            int len = client.receive(buffer(buf, BUFLEN), 0, error);
            cout << "main(): buf.data()=";
            cout.write(buf.data(), len);
            cout << endl;
            boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
        }
    }
    catch (system_error& exc)
    {
        cout << "main(): exc.what()=" << exc.what() << endl;
    }
    return EXIT_SUCCESS;
}

套接字每次都在循环中创建,因为Google(使用它的IP地址)在每次请求后关闭连接(返回状态302)。

在某些情况下,HTTP连接不需要被服务器关闭,所以socket可以被重用。