c++从http后端拿数据的demo
从http后端拿数据,并用nlohmann解析数据
main.cpp
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <fstream>
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main() {
auto host = "127.0.0.1";
auto port = "3000";
// auto target = "/task/record/fetch_data/test_task?page=6&page_size=1";
for (int i = 0; i < 10; i++) {
std::stringstream url_stream;
url_stream << "/task/record/fetch_data/test_task?page=" << i << "&page_size=1";
auto target = url_stream.str();
namespace beast = boost::beast;// from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
using tcp = net::ip::tcp; // from <boost/asio/ip/tcp.hpp>
// The io_context is required for all I/O
net::io_context ioc;
// These objects perform our I/O
tcp::resolver resolver(ioc);
beast::tcp_stream stream(ioc);
// Look up the domain name
auto const results = resolver.resolve(host, port);
// Make the connection on the IP address we get from a lookup
stream.connect(results);
// Set up an HTTP GET request message
http::request<http::string_body> req{http::verb::get, target, 11};
req.set(http::field::host, host);
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
// Send the HTTP request to the remote host
http::write(stream, req);
// This buffer is used for reading and must be persisted
beast::flat_buffer buffer;
// Declare a container to hold the response
http::response<http::string_body> res;
// Receive the HTTP response
http::read(stream, buffer, res);
// std::cout << res.body().c_str() << std::endl;
// Gracefully close the socket
beast::error_code ec;
stream.socket().shutdown(tcp::socket::shutdown_both, ec);
// not_connected happens sometimes
// so don't bother reporting it.
//
if (ec && ec != beast::errc::not_connected) {
std::terminate();
}
// auto f = std::ifstream("/home/hello/下载/response_1697094387779.json");
//
// std::stringstream ss;
// ss << f.rdbuf();
//
// std::cout << ss.str() << std::endl;
std::string json_str = res.body().c_str();
json j = json::parse(json_str);
std::cout << j.dump() << std::endl;
}
return 0;
}
cmakelists
cmake_minimum_required(VERSION 3.26)
project(test_js)
set(CMAKE_CXX_STANDARD 17)
find_package(nlohmann_json)
find_package(Boost REQUIRED)
add_executable(test_js main.cpp)
target_link_libraries(test_js
${Boost_LIBRARIES}
nlohmann_json::nlohmann_json)
tip:
安装nlohmann json
git clone https://github.com/nlohmann/json.git //也可以自己手动下载解压到合适的文件夹下
cd json
mkdir build
cd build/
cmake ..
make
make install
部分命令可能要用sudo进行执行