Twitter, the fun social-networking micro-blogging service, has taken the world by storm. Millions of “tweets” — real-time text messages of up to 140 characters — are posted daily, using several different client applications. Users can read other users’ tweets via the Twitter website, mobile Short Message Service (SMS), Really Simple Syndication (RSS) feeds, and Twitter clients. Twitter clients use a published Twitter API to interact with Twitter servers; this tutorial shows how you can build your own Twitter application to tweet, or search tweets, via the Twitter API.
Twitter is known not only for the simplicity of its concept, but also for its super-cool and easy-to-use API. So let’s quickly try and develop our own desktop Twitter client in three simple steps, producing both a command-line and GUI interface for the Twitter client.
Step 1: Command-line tweeting
Twitter’s simple API allows you to post messages from the command line using cURL. If it’s not installed on your system, use your distribution’s package manager to install it — packages are available for practically every major distro.
An example invocation:
curl --basic --user <username>:<password> --data status=<message> http://twitter.com/statuses/update.xml
Let’s examine the parts of the command:
--basic <username>:<password>
lets you supply your Twitter username and password, for the basic authorisation required by the API.--data status=<message>
will send a POST HTTP request containing your new message, to the URLhttp://twitter.com/statuses/update.xml
. This XML file will be used to send the messages to the user’s account.
To carry out a search via the command line, use a command like the following:
curl http://search.twitter.com/search.atom?q=worldcup
This command will search Twitter for the string “worldcup”, and will return XML from the search page, containing the results.
Step 2: Java program for Twitter
There is a simple function in Java that allows us to execute a Linux command (who cares about Windows!) from within a user program, and retrieve the results, provided the command is installed on the system. Let’s see how the function can be used to execute our very own Linux command to send a tweet:
String s="curl --basic --user"+username+":"+password+"--data status="+ message +"http://twitter.com/statuses/update.xml"; Process p = Runtime.getRuntime().exec(s); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((s = stdInput.readLine()) != null) { System.out.println(s); }
Let’s first create a string to store our command line, concatenating variables for the username, password and message in the necessary order. Next, execute the command using the getRuntime().exec()
function. The output of
the command can be accessed via the getInputStream()
method of the process variable.
You can do a search using the standard Java XML parsing methods, passing the search URL as the XML source. Here is the code for this:
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); URL u = new URL("http://search.twitter.com/search.atom?q=%23worldcup"); Document doc = builder.parse(u.openStream()); String vTemp=null; String vName=null; NodeList nodes = doc.getElementsByTagName("entry"); NodeList temp = doc.getElementsByTagName("author"); for(int i=0;i<nodes.getLength();i++) { Element element = (Element)nodes.item(i); Element element_t = (Element)temp.item(i); vName=getElementValue(element_t,"name").toString(); vTemp+=vName; vTemp+=getElementValue(element,"title").toString(); }
Step 3: Desktop client
Now we have a Java program to post tweets; let’s add a GUI, using the NetBeans IDE, and make it more usable and professional-looking. First, create a new “Java Desktop Application” using the NetBeans new project wizard. You will see a blank window/palette to design your form. Insert a tabbed plane to the blank window. Create one more tab, and add two panels in each of the two tabs. In one of the panels, add three text boxes, with the corresponding labels, and the push-button “Tweet”. In another panel, add a text box with a label, a text area and the push button “Search”. After completing the design, the GUI should look something like what’s shown in Figure 1.
Once the UI is done, go to the events of the Tweet and Search buttons. For the mouse-click event, add the corresponding code from Step 2. Replace the variables for the username, password and message with the string values from the input fields in the form. For example, replace the username variable with jUsername.getText()
(where jUsername
is the name of the text box for the username).
The final code for sending a tweet will look something like what’s given below:
private void jButton2MouseClicked(java.awt.event.MouseEvent evt) { String message = jMessage.getText().toString().replaceAll(" ","%20"); String s = "curl --basic --user "+ jUsername.getText()+":"+jPasswd.getText()+" --data status="+message+" "+"http://twitter.com/statuses/update.xml"; Process p = Runtime.getRuntime().exec(s); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((s = stdInput.readLine()) != null) { System.out.println(s); } System.exit(0); }
Tip: The replaceAll
function replaces all spaces with %20
. This is done to URL-encode spaces with %
followed by the ASCII hexadecimal equivalent code, since spaces cannot be sent in the HTTP request.
To retrieve the search items, the string vTemp
in the search code in Step 2 can be passed to the text area in the search tab, using:
jResult.setText(vTemp);
Thus, using the simple Twitter API and an easy-to-use Java IDE, you can develop a Twitter client in just a few minutes. With some more tweaking and additions to the code, you can easily add other features such as re-tweeting, direct messages, follow/unfollow, and URL shortening. You can download the source code of the tutorial from http://code.google.com/p/twidesk/.