HttpClientクラスを使うとRSSフィードを取得するのがラクにできる。
ただ、Document から SyndFeed を生成する方式だと IllegalAddException が出て失敗することがあるので (たぶんRSS1.0で失敗している?) Response#asString -> SyndFeed を利用している。
import java.io.*;
import java.util.*;
import org.w3c.dom.Document;
import com.sun.syndication.feed.synd.*;
import com.sun.syndication.io.*;
import twitter4j.http.HttpClient;
import twitter4j.http.Response;
public class Utils {
public static List<SyndEntry> getEntries(String feedurl){
try{
HttpClient http = new HttpClient();
Response res = http.get(feedurl);
SyndFeedInput sfi = new SyndFeedInput();
//Document doc = res.asDocument(); // たぶんRSS1.0で失敗
//SyndFeed sf = sfi.build(doc); // たぶんRSS1.0で失敗
String xmlcontent = res.asString();
ByteArrayInputStream bais =
new ByteArrayInputStream(
xmlcontent.getBytes("UTF-8"));
SyndFeed sf = sfi.build(new XmlReader(bais));
List<SyndEntry> entries = sf.getEntries();
return entries;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
}
Ref. ヅラずれなるままに(2009-01-03) - ROME経由でJDOMにRSS1.0文書を渡すとIllegalAddExceptionが発生する
tags: Java zurazure
Posted by NI-Lab. (@nilab)