Retrofit 2 – How to parse rss feed in android

Learn to parse rss feed in an android app using Retrofit 2 using xml parsing with simple xml converter dependency.

In this example, we will be reading and parsing the rss of this blog. A sample feed entry is given below:

<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">
	<channel>
		<title>HowToDoInJava</title>
		<atom:link href="https://howtodoinjava.com/feed/" rel="self" type="application/rss+xml"/>
		<link>https://howtodoinjava.com</link>
		<description/>
		<lastBuildDate>Tue, 27 Aug 2019 17:22:53 +0000</lastBuildDate>
		<language>en-US</language>
		<sy:updatePeriod> hourly	</sy:updatePeriod>
		<sy:updateFrequency> 1	</sy:updateFrequency>
		<generator>https://wordpress.org/?v=5.2.2</generator>
		<image>
			<url>https://howtodoinjava.com/wp-content/uploads/2015/05/
				howtodoinjava_logo-55696c1cv1_site_icon-32x32.png</url>
			<width>32</width>
			<height>32</height>
		</image>
		<item>
			<title>Retrofit 2 – How to parse sitemap in android</title>
			<pubDate>Tue, 27 Aug 2019 17:22:53 +0000</pubDate>
			<description><![CDATA[<p>...</p>]]></description>
			<link>https://howtodoinjava.com/retrofit2/retrofit-parse-sitemap/</link>
		</item>
		'''
		'''
	</channel>
</rss>

1. Dependency

To enable to parsing rss in android, we need at least two dependencies i.e. retrofit and converter-simplexml.

dependencies { 
    compile 'com.squareup.retrofit2:retrofit:2.6.1'
    compile 'com.squareup.retrofit2:converter-simplexml:2.6.1'
}
<dependency>
	<groupId>com.squareup.retrofit2</groupId>
	<artifactId>retrofit</artifactId>
	<version>2.6.1</version>
</dependency>
<dependency>
	<groupId>com.squareup.retrofit2</groupId>
	<artifactId>converter-simplexml</artifactId>
	<version>2.6.1</version>
</dependency>

2. Rss feed model

Start by creating model for consuming the rss feed entry items.

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root(name = "rss", strict = false)
public class RssFeed 
{
	@Element
    public RssChannel channel;
	
	@Override
	public String toString() {
		return "RssFeed [channel=" + channel + "]";
	}
}
import java.util.List;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;

@Root(name = "channel", strict = false)
public class RssChannel 
{
	@Element
	private String title;
	
	@Element
	private RssImage image;
	
	@ElementList(inline = true, required = false)
    public List<RssItem> item;

	@Override
	public String toString() {
		return "Channel [image=" + image + ", item=" + item + "]";
	}
}
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root(name = "image", strict = false)
public class RssImage 
{
	@Element
	private String url;
	
	@Element
	private String width;
	
	@Element
	private String height;
	
	@Override
	public String toString() {
		return "RssImage [url=" + url + ", width=" + width + ", height=" + height + "]";
	}
}
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root(name = "item", strict = false)
public class RssItem 
{
	@Element
	private String title;
	
	@Element
	private String link;
	
	@Element
	private String pubDate;
	
	@Element
	private String description;
	
	@Override
	public String toString() {
		return "RssItem [title=" + title + ", link=" + link + ", pubDate=" + pubDate
				+ ", description=" + description + "]";
	}
}

3. RSS service interface

Create service interface which will be invoked by retrofit to execute rss request. Notice the API URL is '/feed'.

import retrofit2.Call;
import retrofit2.http.GET;

public interface RssService 
{
	@GET("feed") Call<RssFeed> getFeed();
}

4. Retrofit parse rss feed example

Let’s create a retrofit instance and execute the rss request. Given example uses the async request example.

import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;

public class RssServiceDemo 
{
	private static final String BASE_URL = "https://howtodoinjava.com/";

	private static Retrofit.Builder builder = new Retrofit.Builder().baseUrl(BASE_URL)
			.addConverterFactory(SimpleXmlConverterFactory.create());

	private static HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor()
			.setLevel(HttpLoggingInterceptor.Level.BODY);

	private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

	public static void main(String[] args) throws IOException 
	{
		httpClient.addInterceptor(loggingInterceptor);
		builder.client(httpClient.build());

		Retrofit retrofit = builder.build();

		RssService rssService = retrofit.create(RssService.class);

		Call<RssFeed> callAsync = rssService.getFeed();

		callAsync.enqueue(new Callback<RssFeed>() {
			@Override
			public void onResponse(Call<RssFeed> call, Response<RssFeed> response) {
				if (response.isSuccessful()) {
					RssFeed apiResponse = response.body();
					// API response
					System.out.println(apiResponse);
				} else {
					System.out.println("Request Error :: " + response.errorBody());
				}
			}

			@Override
			public void onFailure(Call<RssFeed> call, Throwable t) {
				if (call.isCanceled()) {
					System.out.println("Call was cancelled forcefully");
				} else {
					System.out.println("Network Error :: " + t.getLocalizedMessage());
				}
			}
		});
	}
}

Above program prints the RssFeed instance populated with information set be rss feed.

Drop me your questions related to reading rss feed in android app using Retrofit 2.

Happy Learning !!

Leave a Reply

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial