Thursday, August 29, 2013

Quick Notes on Android RSS

This is a quick and dirty post for a very small user base, but I figured it's been a while so I thought I'd throw up something new.

I am building a podcast app in android, and I'm using Android Annotations (AA) for the feed reading. AA uses Spring Android for the rest (de)serialization, which uses the Android ROME Feed Reader for the various rss formats, which is what I need for my podcasts. Everyone follow that chain of dependencies? Good. Don't forget JDom at the end or ROME blows up. ;-)

So AA allows me to set the converter for reading the xml like so:
@Rest(rootUrl = "", converters = { SyndFeedHttpMessageConverter.class,  })
The problem here is SyndFeedHttpMessageConverter only supports application/atom+xml and application/rss+xml out of the box. And anyone who's ever tried to consume web code knows that everyone and their mother has a content type to use because the format is pretty open. So you wind up with rss or atom sites with contentTypes of application/xml or text/xml, which will fail.

AA doesn't let you set the accepted media types, however, at least not as of version 2.7.1 - so you are forced to leave them behind, which is what I did here. All you have to do is copy out the AA generated code and make your changes, but it's not easy to figure out that that's an actual shortcoming of AA, hence this post. Here's my new shiny code, with the changes in bold:
public class PodcastReaderProxy2
{
    private RestTemplate restTemplate;
    private String rootUrl;
    public PodcastReaderProxy2() {
        restTemplate = new RestTemplate();
        SyndFeedHttpMessageConverter converter = new SyndFeedHttpMessageConverter();
        List<MediaType> supportedTypes = new ArrayList<MediaType>();
supportedTypes.addAll(converter.getSupportedMediaTypes());
supportedTypes.add(MediaType.APPLICATION_XML);
supportedTypes.add(MediaType.TEXT_XML);
converter.setSupportedMediaTypes(supportedTypes);
restTemplate.getMessageConverters().add(converter);
        rootUrl = "";
    } 
    public void setRootUrl(String rootUrl) {
        this.rootUrl = rootUrl;
    } 
    public SyndFeed getFeed() {
        HttpHeaders httpHeaders = new HttpHeaders();
        HttpEntity<Object> requestEntity = new HttpEntity<Object>(httpHeaders);
        return restTemplate.exchange(rootUrl.concat(""), HttpMethod.GET, requestEntity, SyndFeed.class).getBody();
    }
}
 Hopefully this post saves someone else doing REST with AA some time: while my example is focused on podcasts, it's definitely helpful to anyone looking to add some additional supported media types to their web calls.

Some Links:
https://github.com/excilys/androidannotations/wiki/Rest-API#rest
http://www.springsource.org/spring-android
http://static.springsource.org/spring-android/docs/1.0.x/reference/htmlsingle/

Happy Coding!

No comments:

Post a Comment