这是一个用开源包rss4j组件通过解析网络上指定URL地址的RSS文件的例子。
不是很复杂,但是可以通过这个思路进行扩展,开发出自己的RSS聚合器。
外部包:
名称 | 用途 | 下载地址 | |
RSS4J | 解析RSS文档 | http://repo1.maven.org/maven2/rss4j/rss4j/0.92/rss4j-0.92.jar | |
package com.moresee.rss;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import com.rsslibj.elements.Channel;
import com.rsslibj.elements.Item;
import com.rsslibj.elements.RSSReader;
import electric.xml.ParseException;
/**
* RssDemo Author: Tony Tang Email:tangren1206@163.com homepage:<a
* href="http://www.51etest.com">www.51etest.com</a>
*/
public class RssDemo {
private static final String FEED_TYPE = "RSS";
private String urlStr;
public static void main(String[] args) {
new RssDemo();
}
public RssDemo() {
try {
urlStr = "";
grab(urlStr);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void grab(String urlstr) throws FileNotFoundException {
URL url = null;
InputStream is = null;
Channel channel = null;
BufferedReader reader = null;
try {
RSSReader rssReader = new RSSReader();
url = new URL(urlstr);
is = url.openStream(); // 打开指定URL的输入流,即获取此URlRSS的内容
reader = new BufferedReader(new InputStreamReader(is)); // 把字节流形式的数据转换成字符流
rssReader.setReader(reader); // 把此rss数据流的读取器set到RSSReader中去
channel = rssReader.getChannel(); // 获取RSS的Channel
System.out.println(channel.getFeed(FEED_TYPE));
List<Item> items = channel.getItems();
for (Iterator<Item> iter = items.iterator(); iter.hasNext();) {
Item item = iter.next();
System.out.println(item.getTitle());
}
} catch (ParseException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
email: tangren1206@163.com