Rabu, 13 Oktober 2010

How To Get All Posts of a Blog Via Blogger API

Q: I'd like to get all posts of my blog hosted on Google's Blogger via their Java API. How?

I have a blog that has less than 1000 entries and I'd like to get them all programmatically via Blogger Java API, and I setMaxResults(1000) of my Query object thinking that it would return all entries of my blog. But it DID NOT!! How frustrating! And Blogger API or their documentation or tutorial says nothing about it I find it unreasonable; so I have to address this issue.

Solution
After some tweaking I found that if you setMaxResults() to more than 500 you only get back 500 Entry objects, each representing a feed specified by a Feed URL. Then what do you do? Simple. Get 500 entries at a time and get as many times as you need to retrieve all posts of your blog (or feeds of any Google service). This can be done because the results returned are put in the post date order with more recent entries first. Each time you grab a batch of entries you specify an incremental start index via setStartIndex(). So code wise you'd specify your Blogger's blog's URL, use it to create a Query, set the Query's properties and use BloggerService to retriev the Feed and its list of entries. Here's some code to help you out.

public Collection getAllPostsViaApi() throws ServiceException, IOException {
// Request the feed
URL feedUrl = new URL("http://www.blogger.com/feeds/[your-blog-id]/posts/default");

Collection allEntries = new ArrayList();
Query myQuery = new Query(feedUrl);
int startIndex=1; // one based
BloggerService service = new BloggerService("service-name");
while(true){
myQuery.setStartIndex(startIndex);
myQuery.setMaxResults(500);
Feed resultFeed = service.getFeed(myQuery, Feed.class);
List thisBatch = resultFeed.getEntries();
if(thisBatch.isEmpty()){
break;
}else{
allEntries.addAll(thisBatch);
startIndex+=thisBatch.size();
}
}
return allEntries;
}


Questions? Let me know! It should be straightforward but if there's anything unclear leave me a comment and I'll get back to you as soon as I can!

0 komentar:

 
support by: infomediaku.com