Monday, June 20, 2011

Fetch Twitter friends or followers through REST API in Java

I was playing around with fetching Twitter followers and friends with Twitter4J. But it was taking time to do that. So I code it with using REST urls given by Twitter. It fetches all your friends or followers. Depending upon your application that you want one list or you want to use paging. But I did it in one go. Performance wise, it will be trouble of fetching say 2000 followers or friends.

I used JDOM to parse XML.

import java.util.ArrayList;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public class Twt {
String urlFlwrs= "";
String urlFrnds= "";
List followers = new ArrayList();
long cursorCounter = -1;
public static void main(String[] args) {
long start = System.currentTimeMillis();
new Twt().readFollowFriends();
System.out.printf("Total Time: %d secs",
(System.currentTimeMillis() - start)/1000);
void readFollowFriends(){
try {
StringBuffer followersData = new StringBuffer();
// use urlFrnds as a parameter if you want to fetch friends
URL url = new URL(urlFlwrs+cursorCounter);
URLConnection urlConnection = url.openConnection();
DataInputStream dis = new DataInputStream(
String inputLine;
while ((inputLine = dis.readLine()) != null) {
SAXBuilder builder = new SAXBuilder();
Document document = ByteArrayInputStream(
Element root = document.getRootElement();
Element usersElm = root.getChild("users");
Element nextCursor = root.getChild("next_cursor");
List users = usersElm.getChildren("user");
for (int c = 0; c < users.size(); c++) {
Element user = (Element) users.get(c);
Element name = user.getChild("name");
// now you have every thing, the information of a user
// here you can populate followers list
if (nextCursor != null){
cursorCounter = Long.parseLong(nextCursor.getText());
if (cursorCounter != 0)
} catch (Exception e) {

No comments:

Post a Comment