通过提升从流中读取 XML 时出错
error when read xml from a stream by boost
我正在尝试从 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
相关文章:
- c++ 读取 xml 文件的内容
- 从路径中读取 xml
- 结束标记 xml 验证在提升 ptree 读取 xml 中不正确
- Boost Read_graphml 无法正确读取 xml,它给出了所有顶点,但它们是空的
- 通过提升从流中读取 XML 时出错
- 通过Qt读取xml
- 如何在OpenCV中读取XML字符串
- 在 c++ 中读取 xml 文件
- 如何在c++中读取xml
- QT正在读取XML文件,结构
- 读取 XML 值非常简单.C++
- c ++如何使用boost xml解析器读取XML并存储在map中
- 从 C++ / Unix 中的字符串中读取 XML
- 使用 xerces 读取 XML:获取类型,其中 <nodeName type= "typeName" >
- 在C++程序中读取XML文件
- QT:读取xml文件并使用DOM解析器对其进行解析
- 使用 xerces 读取 xml 属性的值
- 读取xml时出现越界错误
- 我想读取XML文件并将其存储到c++的本地字符串变量中
- 使用QXmlStreamReader读取XML文件