In this Retrofit2 tutorial, we will learn to parse RSS feeds in an Android application using Retrofit2 and the SimpleXmlConverterFactory. Retrofit 2 makes HTTP requests easy, while the Simple XML Converter simplifies the parsing of XML responses.
1. RSS Feed
To demonstrate, we’ll parse the RSS feed of this blog.
<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>
2. Maven
To enable RSS parsing in an Android application, you need two essential dependencies: Retrofit 2 and Simple XML Converter. These libraries simplify HTTP communication and XML response parsing.
Add the following dependencies to your build.gradle
file:
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.6.1'
implementation '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>
3. RSS Feed Model
Start by creating a 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 + "]";
}
}
4. RSS Service Interface
Create a service interface that Retrofit will use to fetch the RSS feed. Notice that the URL endpoint for the RSS feed is /feed
.
import retrofit2.Call;
import retrofit2.http.GET;
public interface RssService {
@GET("feed")
Call<RssFeed> getFeed();
}
5. Retrofit parse rss feed example
Finally, we create a Retrofit instance and use it to fetch and parse the RSS feed. The following example demonstrates an asynchronous request.
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();
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());
}
}
});
}
}
The above program prints the RssFeed instance populated with the information set by the RSS feed.
6. Conclusion
This tutorial taught us to parse RSS feeds in an Android application using Retrofit 2 and the Simple XML Converter. We covered setting up dependencies, creating model classes, defining a service interface, and using Retrofit to fetch and parse the feed.
Drop me your questions about reading the RSS feed in the Android app using Retrofit 2.
Happy Learning !!
Comments