通过提升从流中读取 XML 时出错

error when read xml from a stream by boost

本文关键字:读取 XML 出错      更新时间:2023-10-16

我正在尝试从 ip-api.com 获取XML响应以获取一些信息。但我不知道为什么我不能从字符串流中读取 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.0rn";
stream << "Host: ip-api.comrn";
stream << "Accept: */*rn";
stream << "Connection: closernrn";
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 响应标头开头。下面是一段包含这些检查的简化代码:

#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.0rn";
    stream << "Host: ip-api.comrn";
    stream << "Accept: */*rn";
    stream << "Connection: closernrn";
    stream.flush();
    std::string const response(std::istreambuf_iterator<char>(stream), {});
    auto headersEnd = response.find("rnrn");
    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