用到的jar包为jdom.jar,rome-0.9.jar
package com.gary.util.rss;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.List;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
/**
* RSS/Atom
* 支持从文件或URL读取
* @author gary
*
*/
public class FeedReader {
public static void main(String[] args) {
String source = "http://www.oschina.net/project/rss";
// String source = "rss_local_example.xml";
try {
//输出发布日期,链接,标题等内容,可自定义
String[] outputContent = {"publishedDate","link","title"};
print(read(source).getEntries(), outputContent);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (FeedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
/**
* 输出
* @param entries 内容
* @param args要输出的列名称
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void print(List entries, String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
for (int i = 0; i < entries.size(); i++) {
SyndEntry entry = (SyndEntry) entries.get(i);
Object o = entry;
Class extends Object> cls = o.getClass();
Method m = null;
for (int j = 0; j < args.length; j++) {
String methodName = "get" + args[j].substring(0,1).toUpperCase() + args[j].substring(1);
m=cls.getMethod(methodName, null);
System.out.println(args[j]+":"+m.invoke(o, null));
}
System.out.println("==========================================");
}
}
/**
* 读取
* @param source 目标
* @return
* @throws IOException
* @throws FeedException
* @throws IllegalArgumentException
*/
public static SyndFeed read(String source) throws IllegalArgumentException, FeedException, IOException{
//SyndFeedInput:从远程读到xml结构的内容转成SyndFeedImpl实例
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = null;
if(source.startsWith("http")){
URL feedUrl = new URL(source);
//rome按SyndFeed类型生成rss和atom的实例,
//SyndFeed是rss和atom实现类SyndFeedImpl的接口
feed = input.build(new XmlReader(feedUrl));
}else{
File feedUrl = new File(source);
feed = input.build(new XmlReader(feedUrl));
}
return feed;
}
}
?
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- huatuo9.cn 版权所有 赣ICP备2023008801号-1
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务