I'm new to Java and Spring boot and I am trying to read and Parse RSS feed from a site.
What's the issue: I need to read all the data from the feed and it'll be the paginated call.
What's my solution: I think, I can achieve it if I read the data in a loop unless I reach the end and there's no more data. My code is as:
SyndFeedInput input = new SyndFeedInput();
int pageNumber = 1;
do {
URL feedSource = new URL("https://altaonline.com/feed?paged=" + pageNumber);
SyndFeed feed = input.build(new XmlReader(feedSource));
pageNumber = pageNumber + 1;
}
while ( pageNumber <= 27); //Need to fix this.
I need help with: If there's no data on this URL, it gives me exception. I am not sure, how to check if the URL is valid, or if there's any data to process. How to do it
You wouldn't know if the URL is valid unless you make the http request. So in this case, it would be ideal to surround the code with a try-catch
and handle the exception accordingly. In case the URL isn't valid or returning no data, it can be handled by catching IOException
. In case the feed returned cannot be parsed or generated, it can be handled by catching FeedException
.
SyndFeedInput input = new SyndFeedInput();
int pageNumber = 1;
try{
do {
URL feedSource = new URL("https://altaonline.com/feed?paged=" + pageNumber);
SyndFeed feed = input.build(new XmlReader(feedSource));
pageNumber++;
}
while (pageNumber <= 27);
} catch (IOException ex){
System.out.println("IO exception occurred due to: "+ ex);
//Handle this exception accordingly
} catch (FeedException ex) {
System.out.println("Feed exception occurred due to: "+ ex);
//Handle this exception accordingly
}
You may even catch Exception
at the bottom for handling any other unknown exceptions that may occur. Please note that System.out.println
is only given as an example and ideally should be replaced by using a logging library.