我正在尝试使用 RSS 并解析它。我找到了 Rome ,我正在尝试通过代码使用它:
private SyndFeed parseFeed(String url) throws IllegalArgumentException, FeedException, IOException {
return new SyndFeedInput().build(new XmlReader(new URL(url)));
}
public Boolean processRSSContent(String url) {
try {
SyndFeed theFeed = this.parseFeed(url);
SyndEntry entry = theFeed.getEntries().get(0);
ZonedDateTime entryUtcDate = ZonedDateTime.ofInstant(entry.getPublishedDate().toInstant(), ZoneOffset.UTC);
String entryTitle = entry.getTitle();
String entryText = entry.getDescription().getValue();
}
catch (ParsingFeedException e) {
e.printStackTrace();
return false;
}
catch (FeedException e) {
e.printStackTrace();
return false;
}
catch (IOException e) {
e.printStackTrace();
return false;
}
}
在某些 channel 上,如 http://feeds.bbci.co.uk/news/world/rss.xml一切正常,但在其他一些 channel 上,如 http://habrahabr.ru/rss/我收到错误:
Invalid XML: Error on line 5: The element type "meta" must be terminated by the matching end-tag "</meta>".
com.rometools.rome.io.ParsingFeedException: Invalid XML: Error on line 5: The element type "meta" must be terminated by the matching end-tag "</meta>".
我看了一下这个链接后面的内容,XML 确实很奇怪。但它是一个受欢迎的网站,我在其他一些网站上也遇到了这个错误,所以我不认为 XML 存在问题。我做错了什么?如何阅读此 RSS channel ?
最佳答案
如果您输入网址 http://habrahabr.ru/rss/到您的浏览器,您会注意到它重定向到 https://habrahabr.ru/rss/interesting 。您的代码不处理重定向。
我建议您使用HttpClientFeedFetcher来自rome-fetcher模块,它处理重定向并具有其他高级功能(缓存、条件 GET、压缩):
HttpClientFeedFetcher feedFetcher = new HttpClientFeedFetcher();
try {
SyndFeed feed = feedFetcher.retrieveFeed(new URL("http://habrahabr.ru/rss/"));
System.out.println(feed.getLink());
} catch (IllegalArgumentException | IOException | FeedException | FetcherException e) {
e.printStackTrace();
}
编辑:Rome-fetcher is being deprecated ,但是可以使用Apache HttpClient来代替,而且更加灵活。
关于Java- Rome : I am trying to parse RSS feed but get a error on some channels,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35104839/