Friday, November 6, 2009

JAVA: Retrieving List of Blog Posts Using Blogger Data API

You can use the Java Blogger Data API to display the list of blog entries.

First you need to download the Java client library. You'll find the classes you need to use in the java/lib/gdata-core-1.0.jar file.

GData Java Client Library has the following external dependencies which you also need to add
1. java/deps/google-collect-1.0-rc1.jar
2. java/deps/jsr305.jar

Finally, add the following sample code to display the list of blog entries.
import java.io.IOException;
import java.net.URL;
import java.util.LinkedList;

import com.google.gdata.client.GoogleService;
import com.google.gdata.data.Entry;
import com.google.gdata.data.Feed;
import com.google.gdata.data.HtmlTextConstruct;
import com.google.gdata.data.TextContent;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;


public class Blogger {
public static void main(String[] args)
{
String username = "#@gmail.com";
String userpass = "#";
String feed ="http://www.blogger.com/feeds/#blogid/posts/default";

try{
URL feedUrl = new URL(feed);
GoogleService myService = new GoogleService("blogger", "bprddd");

//Set up authentication (optional for beta Blogger, required for current Blogger):
myService.setUserCredentials(username, userpass);

//Send the request and receive the response:
Feed myFeed = myService.getFeed(feedUrl, Feed.class);

System.out.println(myFeed.getTitle().getPlainText());
LinkedList<Entry> entries = (LinkedList<Entry>)myFeed.getEntries();
int itemsPerPage = myFeed.getItemsPerPage();

Entry entry ;
for(int i=0; i < itemsPerPage; i++){
entry = (Entry)entries.get(i);
System.out.println(entry.getId());
System.out.println(entry.getTitle().getPlainText());
System.out.println(entry.getPublished().toUiString());
System.out.println(entry.getUpdated().toUiString());
TextContent tc = (TextContent)entry.getContent();
HtmlTextConstruct ptc = (HtmlTextConstruct)tc.getContent();
System.out.println(ptc.getHtml());
}
}
catch (AuthenticationException e) {
e.printStackTrace();
}catch (ServiceException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}