使boost http客户端
Make boost http client
我是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可以被重用。
相关文章:
- 使用 c++ 的 http 客户端的默认方法
- 在客户端和备忘录中获取 HTTP 命令
- 在 MySQL 中运行 HTTP 服务器以从客户端接收数据
- Waveshare 电子纸 ESP32 板上的 HTTP 客户端管理问题
- 节点.js HTTP 无法通过套接字接收来自C++客户端的请求
- C++HTTP客户端在GET请求后挂起read()调用
- 为什么 JsonCpp http 客户端在 201 响应代码上失败?
- boost :: Beast Sync http客户端的超时
- 异步WT :: HTTP ::客户端响应和请求匹配
- 使用带有SSL(HTTPS)的Boost-Beast(ASIO)HTTP客户端
- 当发送多个同时请求时,单线程异步系统中Beast Boost异步HTTP客户端的行为
- 基于BOOST :: ASIO-慢慢http客户端 - (转移块)
- 如何对 HTTP 客户端进行测试
- 简单的C 异步HTTP客户端
- 是否可以更改HTTP客户端超时期限(cpp-netlib)
- 用于C++的Google API客户端库与用于发送HTTP请求的libcurl
- HTTP 请求使用 Google API 客户端库进行C++
- Wt::Http::客户端始终以 throw_exception<boost::bad_weak_ptr>() 结尾
- Websocketpp简单HTTP客户端
- 从Poco http客户端获取对字符串的响应