Monday, 20 June 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.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.net.URL;
import java.net.URLConnection;
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= "http://twitter.com/statuses/followers/YOUR_TWITTER_SCREEN_NAME.xml?cursor=";
String urlFrnds= "http://twitter.com/statuses/friends/YOUR_TWITTER_SCREEN_NAME.xml?cursor=";

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(
urlConnection.getInputStream());
String inputLine;
while ((inputLine = dis.readLine()) != null) {
followersData.append(inputLine);
}

SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new ByteArrayInputStream(
followersData.toString().getBytes()));

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)
readFollowFriends();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

No comments:

Post a Comment