Pages Navigation Menu

Coding is much easier than you think

RSS feeds Using Java

Posted by in Java, RSS Feed | 1 comment

 
RSS feeds are always becoming used more and more. Using RSS feeds is a good way to keep updated on a particular subject, it is also a very good way to keep a website always updated without the need of manual updates. RSS feeds are very easy to install into a website and with their help, your website will never be out of date!
 
In order to add RSS feeds to your website, the below code can be used
 
Assuming we want the latest RSS feeds about sports. We would primarily need the URL of the feeds.

In our case we will be using the following link providing Yahoo RSS:

http://news.yahoo.com/rss/sports

 
Before start, Please download below library

 

dwd2
Rome 1.0
JDOM 1.0

 
File : RssFeed.java
 
package com.simplecode;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
import java.net.URL;
import java.util.List;

public class RssFeed {

	public static void main(String[] args) {
		String printFeeds = getRSSfeeds("http://news.yahoo.com/rss/sports");
		System.out.println(printFeeds);
	}

	@SuppressWarnings({ "rawtypes", "finally", "unused" })
	protected static String getRSSfeeds(String feedUrl) {
		StringBuffer sb = new StringBuffer();
		try {
			URL url = new URL(feedUrl);
			SyndFeedInput input = new SyndFeedInput();
			SyndFeed feed = input.build(new XmlReader(url));
			List list = feed.getEntries();
			if (list.size() > 0) {
				for (int j = 0; j < list.size(); j++) {
					String container = "<p class=\"RSSlist\">";
					sb.append(container);
					String title = ((SyndEntry) list.get(j)).getTitle();
					sb.append(title + "\n");
					String link = ((SyndEntry) list.get(j)).getLink();
					String readmore = " Read more ";
					sb.append(readmore);
					String endContainer = "";
					sb.append(endContainer);
				}
			}
		}

		catch (Exception e) {
			System.err.print("Exception");
		}

		finally {
			return sb.toString();
		}

	}
}

 

Finally all code is ready. All is left to do is to call the RSS feed method from the JSP files by using where ever desired on the page. This will display the title and a read more link.
 

dwd2

Download It – €“RssFeed Example file


  Read More