我是 boost library 的新手,所以我的问题可能不是这个论坛中的第一个问题,但我找不到类似的案例。 目前我正在尝试实现一个调用 REST API 的简单 HTTP 客户端。 我从 boost 网站上给出的例子中得到启发:HTTP client with boost
这个例子对于像我这样的新手来说已经足够清楚了,但是我想让客户端能够一个一个地执行多个请求,因为这个例子是一次性的:客户端向服务器发送一个 GET 请求,然后它收到响应,然后 io_service.run() 返回。
所以我的问题是我需要使用 boost 的方式让我的客户始终等待新请求发送。
我阅读了一些关于 io_service::work 的内容,但我不确定它是否是正确的方法。
有没有人做过与我正在尝试制作的客户端类似的东西? 提前致谢!
最好的问候,
安东
最佳答案
不知道异步版本是不是必须的,所以我建议你试试同步版本,因为它更容易遵循执行路径:
/*
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.0\n\n";
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 连接不必由服务器关闭,因此可以重用套接字。
关于c++ - 制作 boost http 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39225919/