Advertisment

Auto Tweet on Twitter Using Java

author-image
PCQ Bureau
New Update

The popularity of Twitter, Facebook or MySpace amongst Internet user has
increased by many folds. Even several enterprises have started using these
social networking platforms as a platform to interact with their customers. Many
of these offer open APIs which allow you to integrate your own application to
their application platform. Twitter is one such popular social networking site,
better known as a microblogging site. Twitter allows people to send a brief
update (tweet), about what they are doing and that tweet is visible to their
followers and friends. Twitter also offers an open application interface through
which you can access Twitter from your own application.

Advertisment

Direct Hit!

Applies To: Java Developers

USP: Tweet with Java library

Primary Link: http://tinyurl.com /myz33r
Keywords:
Twitter4J, Java library for TwitterAPI

About Twitter4J

Many enterprises use Twitter to send updates about their products and services.
Using Twitter APIs, they can integrate their intranet portals to Twitter and
post updates directly from there without going to the main Twitter website.
Twitter4J is a Java library for Twitter API. This readymade set of libraries
allow you to query Twitter for various aspects. For instance, you can create a
Java based web application that you can integrate with the organizations portal
which will allow users to see the latest Twitter updates for their organization
or company. Twitter4J is completely implemented in Java and spares you the
hassles of creating your own wrapper for Twitter APIs for your Java application
to access Twitter. It allows all the functionalities for accessing Twitter, and
is easy to use. Here, we will demonstrate how you can use Twiter4J to access
Twitter through a Servlets Web application.

Getting Started

To start building your web application that will access Twitter, you need to
download Twitter4J from the URL provided in the Direct-Hit box. The current
version of Twitter4J is 2.0.8 which was released in mid June and has a bug fix
over the previous version that used to give a NumberFormatException error while
fetching user timelines from Twitter. Once you download Twitter4J package from
the website, extract it into a folder, and in the extracted contents you can
find the Twitter4J library along with documentation and examples. Using
Twitter4J is simple. You just have to add the twitter4j-2.0.8.jar library to
your application's classpath or into your project's refered libraries.

Advertisment
While creating the project,
choose the Target Runtime as the server on which you will run your project.
To add a server follow the steps as shown in the visual.

Twitter4J requires Java platform version 1.4.2 or later. For this
demonstration, we will create the web application in a development environment
having Eclipse 3.4 with JDK 1.6 installed and using Tomcat 6.0 as the
application server. The application which we'll create will be using Twitter4J
to access Twitter to send an status update and will also fetch messages from the
user's friends timeline.

Create a new project in Eclipse by going to File > New > Other, and in the
New window expand the Web option to select Dynamic Web Project and click on Next
button. On the following Dynamic Web Project wizard screen, enter the project's
name as TweetTry and select the target runtime for the project, which will be
Tomcat 6.0. Click Finish which will create the project.

Advertisment
The twitter4j-2.0.8.jar is added
to the projects referenced libraries so that the project can access the
Twitter APIs

To add a new target runtime as your application's server, click on New button
within the Target Runtime frame and on the following screen, select Tomcat 6.0
under the Apache list and click Next button.

On the next screen give a name for the server and also pass the path for the
Tomcat Installation Directory along with the JRE that will be used by the
server.

Advertisment

Using twitter4j.Twitter

Once the project is created we can start writing our first servlet. To create
the servlet, right click on the project name in the Project Explorer view and
select New > Servlet. In the corresponding screen, name the servlet as TweetDemo
and give the Java package as com.examples.pcq, and click Finish. The servlet
will be created with stubs for doGet() and doPost() methods to be overwritten by
our codes. In the Project Explorer under the Java Resources > src folder, you
can find the TweetDemo.java file. Open this file, and for the doGet() method we
write the Twitter4J code whereby we will be instantiating an instance for the
twitter4j.Twitter class and pass Twitter ID and password as constructor
arguments. But first in the import statement import the twitter4j.* package so
that the Twitter class and its methods can be used. To send status update to
your Twitter account the updateStatus() method of the Twitter class is used. The
method takes a String parameter as the update message. The following code
snippet shows how to instantiate the Twitter class and send an status update to
the Twitter site through the updateStatus() method.

Twitter twitter = new Twitter(twitterID,twitterPassword);

Status status = twitter.updateStatus(latestStatus);

Fetching Friends Timeline

The twitter4j.Twitter class has three methods to fetch different timelines.
These are getPublicTimeline(), getUserTimeline() and getFriendsTimeline()
methods which returns a list of public, user and user's friends timelines
respectively. For our demo program we want to fetch the recent timeline of the
user's friends. The following code snippet shows the method to fetch friend's
timeline for a giver user:

Advertisment

List statuses = twitter.getFriendsTimeline();

This method returns 20 most recent statuses posted in the last 24 hours from
the authenticating user and that user's friends. The following is the complete
servlet through which we will get the credentials of a user authenticated on
Twitter website and then post that user's status message and will also fetch 20
recent status updates from that user's timeline and will display those on the
browser as output in a formatted manner.

When we run the TweetDemo
servlet, the user's friends timeline is displayed in an HTML formatted
manner as the output
Advertisment

package com.examples.pcq;

import java.io.*;

import java.util.List;

import javax.servlet.*;

import javax.servlet.http.*;

import twitter4j.*;

public class TweetDemo extends
javax.servlet.http.HttpServlet

implements javax.servlet.Servlet {

public TweetDemo() {

super();

}

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

try {

Advertisment

String user=null;

String text=null;

Twitter twitter = new Twitter("username", "password");

Status status = twitter.updateStatus("This is PCQuest demo for Twitter4J");

List statuses = twitter.getFriendsTimeline();

PrintWriter outputToBrowser = new
PrintWriter(response.getOutputStream());

response.setContentType("text/html");

String htmlPage = "Twitter Update and Friends<br> Timeline";

htmlPage += "";

htmlPage += "

ter>

Showing friends timeline:-




";

for(int i=0; i < statuses.size() ; i++) {

Status status1 = (Status)statuses.get(i);

user = status1.getUser().getName();

text = status1.getText();

htmlPage += ""+user+":";

htmlPage += ""+text+"";

htmlPage += "
";

}

outputToBrowser.println(htmlPage);

String htmlPage2 = "

";

htmlPage2 += "
Return to Main Page";

htmlPage2 += "
";

outputToBrowser.println(htmlPage2);

outputToBrowser.close();

} catch (TwitterException ex) {

ex.printStackTrace();

}

}

Formatting the Timeline

The getFriendsTimeline() method returns the list of statuses, and we can iterate
through those statuses list to get each status's user name and the text message
of the status.

Using response.getWriter() we can display the output as text on the browser,
but not in a formatted style. To present the output in as a HTML page we use the
PrintWriter class of the java.io package.

This class implements all of the print methods found in PrintStream, and is
used for print formatted representations for a text output stream. The
PrintWriter will stream the output through the getOutputStream() method of the
ResponseServlet. We will set the content type of the response being sent to the
client as text/html through the ResponseServlet's setContentType() method.

Conclusion

Thus we have created a servlet based application that can send user updates to
twitter and fetch user's friends updates back. Though in our example we have
hard-coded the TwitterID and password, but while creating an application you can
pass the user's Twitter ID and password through a JSP form to the servlet.

Advertisment

Stay connected with us through our social media channels for the latest updates and news!

Follow us: