Retrieving an RSS feed protected by Basic Authentication using ROME

Today I worked on a feature in a Struts web application where I needed to retrieve an RSS feed that is protected by Basic Authentication and then display the the results of the feed in a web page. I’ve heard alot about ROME in the past couple weeks, so I decided to try it out. It quickly passed the 10 minute test (downloaded rome-0.5.jar, downloaded jdom.jar, used the sample code from the tutorial on the wiki); I was able to retrieve, parse and display the results of my own feed in no time:

String feed = "http://cephas.net/blog/index.rdf";
URL feedUrl = new URL(feed);
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build(new XmlReader(feedUrl));
System.out.println(feed);

Easy. But that wasn’t my problem. I needed to be able to set the Basic Authentication header which is usually done like this:

String feed = "http://yoursite.com/index.rdf";
URL feedUrl = new URL(feed)
HttpURLConnection httpcon = (HttpURLConnection)feedUrl.openConnection();
String encoding = new sun.misc.BASE64Encoder().
  encode("username:password".getBytes());
httpcon.setRequestProperty ("Authorization", "Basic " + encoding);
httpcon.connect();
.. // do stuff
httpcon.disconnect();

Turns out that the designers of the ROME library were pretty smart. In addition to including the XmlReader(URL url) constructor, they also included a XmlReader(URLConnection connection) constructor, which allows you to combine the two blocks of code I wrote above to make this:

String feed = "http://yoursite.com/index.rdf";
URL feedUrl = new URL(feed)
HttpURLConnection httpcon = (HttpURLConnection)feedUrl.openConnection();
String encoding = new sun.misc.BASE64Encoder().
  encode("username:password".getBytes());
httpcon.setRequestProperty ("Authorization", "Basic " + encoding);
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build(new XmlReader(httpcon));

Add this code to your Struts action, put the resulting SyndFeed in the request scope (request.setAttribute("feed", feed);) and then in the JSP:

<c:forEach var="entry" items="${feed.entries}">
  <strong>${entry.title}</strong><br />
  ${entry.description.value}<br />
  <fmt:formatDate value="${entry.publishedDate}" type="both" pattern="MMMM dd, yyyy" />
  by ${entry.author} | <a href="${entry.link}">link</a>
</c:forEach>

So there you have it. I hope that makes it easier for someone else!

2 thoughts on “Retrieving an RSS feed protected by Basic Authentication using ROME”

  1. Thank you, that worked very well for me! But Eclipse raised a warning about the used BASE64Encoder which can not be accessed on my Mac’s JDK 7 installation. So I use the Base64 encoder from the Apache Commons Project instead, which works too:

    import org.apache.commons.codec.binary.Base64;

    byte[] encoding = new Base64.encode(“username:password”.getBytes());

Leave a Reply

Your email address will not be published. Required fields are marked *