gpt4 book ai didi

c++ - 通过boost从流中读取xml时出错

转载 作者:太空宇宙 更新时间:2023-11-04 13:03:20 29 4
gpt4 key购买 nike

我正在尝试从 ip-api.com 获取 xml 响应以获取一些信息。但我不知道为什么我不能从 stringstream 中读取 xml。这是我的代码:

boost::asio::ip::tcp::iostream stream;
stream.expires_from_now(boost::posix_time::seconds(60));
stream.connect("ip-api.com", "http");
stream << "GET /xml HTTP/1.0\r\n";
stream << "Host: ip-api.com\r\n";
stream << "Accept: */*\r\n";
stream << "Connection: close\r\n\r\n";
stream.flush();
//std::cout << stream.rdbuf() << std::endl;
char res[255];
std::stringstream ss;
while (!stream.eof()) {
stream.getline(res, 255);
ss << res << "\n";
}
std::cout << ss.str();
boost::property_tree::ptree ntree;
boost::property_tree::read_xml(ss, ntree); <~ exeption in here
boost::property_tree::ptree vals = ntree.get_child("query");
BOOST_FOREACH(auto f, vals) {
if (f.first == "country") std::cout << f.second.data() << std::endl;
if (f.first == "city") std::cout << f.second.data() << std::endl;
if (f.first == "query") std::cout << f.second.data();
}

最佳答案

所以异常读取

terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::property_tree::xml_parser::xml_parser_error> >'
what(): <unspecified file>(1): expected <

从转储响应中可以看出,它以 HTTP 响应 header 开头。下面是一段带有这些检查的简化代码:

#include <boost/asio.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <iostream>

boost::property_tree::ptree ipApiCheck() {
boost::asio::ip::tcp::iostream stream;
stream.expires_from_now(boost::posix_time::seconds(2));
stream.connect("ip-api.com", "80");
stream << "GET /xml HTTP/1.0\r\n";
stream << "Host: ip-api.com\r\n";
stream << "Accept: */*\r\n";
stream << "Connection: close\r\n\r\n";
stream.flush();

std::string const response(std::istreambuf_iterator<char>(stream), {});
auto headersEnd = response.find("\r\n\r\n");
if (std::string::npos == headersEnd)
throw std::runtime_error("Malformed response");

std::istringstream iss(response.substr(headersEnd+4));
boost::property_tree::ptree ntree;
read_xml(iss, ntree);
return ntree;
}

int main() {
auto xml = ipApiCheck();

std::cout
<< "country: " << xml.get("query.country", "?") << "\n"
<< "city : " << xml.get("query.city", "?") << "\n"
<< "query : " << xml.get("query.query", "?") << "\n";
}

打印,例如

country: Zimbabwe
city : Harare
query : 56.155.44.177

关于c++ - 通过boost从流中读取xml时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43342405/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com