Oct 13, 2010

f Comment

Getting Every Post of a Blog Via Google Blogger API!

Amazon 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 myself!

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. Entry is com.google.gdata.data.Entry and Query is com.google.gdata.client.Query.
public Collection<Entry> getAllPostsViaApi() throws ServiceException, IOException {
    // Request the feed
    URL feedUrl = new URL("http://www.blogger.com/feeds/[your-blog-id]/posts/default");

    Collection<Entry> allEntries = new ArrayList<Entry>();
    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<Entry> 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!
Please leave a comment here!
One Minute Information - by Michael Wen
ADVERTISING WITH US - Direct your advertising requests to Michael