Srikanth Technologies

Twitter Client In Java

In this blog, I will show you how to get user timeline (tweets) from twitter.com using Twitter Rest API.

I get the most recently posted tweets of the given user by using Twitter Rest API through three different ways :

Using java.net.URL and Xpath

The following code makes a request to twitter using Twitter's REST API to get tweets in the form of XML. Then I use XPath to get selected nodes from the XML data provided by twitter api.

import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class GetTweets {

    public static void main(String[] args) {
        try {
            URL url = new URL("https://api.twitter.com/1/statuses/user_timeline.xml?screen_name=srikanthpragada&count=5");

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(url.openStream());

            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression expr = xpath.compile("/statuses/status");

            NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

            for (int i = 0; i < nl.getLength(); i++) {
                System.out.printf("%s\n%s\n\n", getElementValue(nl.item(i),"text"), 
                                                getElementValue(nl.item(i),"created_at"));
            }
        } catch (Exception ex) {
             ex.printStackTrace();
        }
    }
    
    public static String getElementValue(Node parent, String name) {
         NodeList list = parent.getChildNodes();
         for ( int i = 0; i < list.getLength() ; i ++)
         {
             if ( list.item(i).getNodeName().equals(name))
                 return  list.item(i).getFirstChild().getNodeValue();
         }
         return null;
    }
}

Using Twitter4J Library

In this example, I use classes provided by Twitter4J library, which takes care of making request to twitter and provides you Java object.

You have to download Twitter4J library from here

Add twitter4j-core-2.2.6.jar to Libraries node of your project.


import java.util.List;
import twitter4j.Paging;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;

public class GetTweetsWithTwitter4J {

    public static void main(String[] args) {
        try {
            Twitter twitter = new TwitterFactory().getInstance();
            Paging p= new Paging();
            p.setCount(5);  // specify you want only 5 most recent entries 
            List<Status> statuses = twitter.getUserTimeline("srikanthpragada",p); // screenname is srikanthpragada
            
            for (Status status : statuses) {
                System.out.printf("%s\n%s\n\n",status.getText(), status.getCreatedAt());  // get text and created_at attributes
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Twitter4J is a huge library with lots of useful API. Please read its documentation to find out what else you can do.

Using JQuery

In this case we get tweets using JQuery, which makes an Ajax request to twitter's JSON API.

Make sure you include .js file related to Jquery (like jquery-1.6.1.js) in Web Pages node in your project in NetBeans IDE.


twitterclient.html

<html> <head> <title>Twitter Client </title> <script language="javascript" src="jquery-1.6.1.js"></script> <script language="javascript"> function getTweets() { url = "https://api.twitter.com/1/statuses/user_timeline.json?callback=?"; $.getJSON(url, { screen_name: $("#screen_name").val(), count: "5" }, displayResult); } function displayResult(data) { var out = ''; for (var i = 0; i < data.length; i++) { out += '<li>' + data[i].text + '<br/> - ' + data[i].created_at + "</li>"; } $("#tweets").html(out); } </script> </head> <body> <h2>Tweets</h2> Enter Screen Name : <input type="text" id="screen_name" size="20" value="srikanthpragada"/> <p/> <input type="button" value="Get Tweets" onclick="getTweets()" /> <p/> <ul id="tweets"></ul> </body> </html>