[英]error when read xml from a stream by boost
我正在嘗試從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響應頭開始。 這是一個帶有這些檢查的簡化代碼:
#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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.