RomeのRSSクイックガイド
1. 概要
RSS(Rich Site SummaryまたはReally Simple Syndication)は、さまざまな場所から集約されたコンテンツを読者に提供するWebフィード標準です。 ユーザーは、お気に入りのブログやニュースサイトなどで最近公開されたものをすべて1か所で確認できます。
また、アプリケーションはRSSを使用して、RSSフィードを介して情報を読み取り、操作、または公開できます。
この記事では、Rome APIを使用してJavaでRSSフィードを処理する方法の概要を説明します。
2. Mavenの依存関係
3. 新しいRSSフィードの作成
まず、Rome APIusing the default implementation SyndFeedImpl of the SyndFeed interfaceを使用して新しいRSSフィードを作成しましょう。 このインターフェイスはすべてのRSSフレーバーを処理できるため、いつでも安全に使用できます。
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType("rss_1.0");
feed.setTitle("Test title");
feed.setLink("http://www.somelink.com");
feed.setDescription("Basic description");
このスニペットでは、タイトル、リンク、説明などの標準のRSSフィールドを使用してRSSフィードを作成しました。 SyndFeed gives the opportunity of adding many more fieldsには、作成者、寄稿者、著作権、モジュール、公開日、画像、外国のマークアップ、言語が含まれます。
4. エントリの追加
RSSフィードを作成したので、エントリを追加できます。 以下の例では、use the default implementation SyndEntryImpl of the SyndEntry interfaceを使用して新しいエントリを作成します。
SyndEntry entry = new SyndEntryImpl();
entry.setTitle("Entry title");
entry.setLink("http://www.somelink.com/entry1");
feed.setEntries(Arrays.asList(entry));
5. 説明の追加
これまでのところエントリはかなり空なので、説明を追加しましょう。 これはusing the default implementation SyndContentImpl of the SyndContent interfaceで実行できます。
SyndContent description = new SyndContentImpl();
description.setType("text/html");
description.setValue("First entry");
entry.setDescription(description);
setTypeメソッドを使用して、説明のコンテンツがテキストまたはHTMLになるように指定しました。
6. カテゴリの追加
RSSエントリは、関心のあるエントリを見つけるタスクを簡素化するために、多くの場合カテゴリに分類されます。 エントリusing the default implementation SyndCategoryImpl of the SyndCategory interface:にカテゴリを追加する方法を見てみましょう
List categories = new ArrayList<>();
SyndCategory category = new SyndCategoryImpl();
category.setName("Sophisticated category");
categories.add(category);
entry.setCategories(categories);
7. フィードの公開
すでにエントリのあるRSSフィードがあります。 ここで公開します。 この記事の目的上、公開とは、フィードをストリームに書き込むことを意味します。
Writer writer = new FileWriter("xyz.txt");
SyndFeedOutput syndFeedOutput = new SyndFeedOutput();
syndFeedOutput.output(feed, writer);
writer.close();
8. 外部フィードを読む
新しいフィードを作成する方法は既に知っていますが、既存のフィードに接続するだけでよい場合もあります。
URLを指定して、フィードを読み取り/ロードする方法を見てみましょう。
URL feedSource = new URL("http://rssblog.whatisrss.com/feed/");
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build(new XmlReader(feedSource));
9. 結論
この記事では、いくつかのエントリを含むRSSフィードの作成方法、フィードの公開方法、および外部フィードの読み取り方法を示しました。
いつものように、この記事over on GitHubで提供されている例を確認できます。