Nicolas Frankel is an IT consultant with 10 years experience in Java / JEE environments. He likes his job so much he writes technical articles on his blog and reviews technical books in his spare time. He also tries to find other geeks like him in universities, as a part-time lecturer. Nicolas is a DZone MVB and is not an employee of DZone and has posted 225 posts at DZone. You can read more from them at their website. View Full User Profile

Java Twitter Integration

  • submit to reddit

During the writing of Learning Vaadin, I create a sample application step-by-step. This application is in fact a Twitter client. Twitter provides a nice API along with its related documentation in order to interact with their site. However, I’d rather deal with a Java API that shields me from all the griity details of the how to let me focus on the what. Hunting for such a component gave me Twitter4j.

During my development with Twitter4j, I was stuck with the authentication process. This article is an attempt at easing the use of Twitter4j so that I’ll be the only one to face such problems.

The first step in using the Twitter API, either directly or through a third-party framework is to register an application. This step is to ensure that only known consumers can potentially access Twitter. An important parameter of our application is its type: client or browser. In the latter case, you’ll have to provide a callback URL, where users will be redirected when successfully authentified. Note that if your application is not web-based or not published (like for a localhost application), it’s imperative that you check client. The process will be entirely different in that users will not be redirected but returned a PIN key that will have to be entered in order to get final authorization. In all cases, creating an application will give us two important pieces of data: the consumer key and the consumer secret, that proves that we registered.

From this point on, we can call Twitter, or more precisely, can delegate authentication to Twitter. The raw process goes something like that:

  1. Ask Twitter for a request token, providing both consumer key and secret
  2. Store the response somewhere
  3. Extract the authentication URL from the response
  4. Redirect the user to the authentication URL, so that he can sign in
  5. This is done outside the application: User signs in and gets the PIN
  6. User enters PIN in application
  7. Ask Twitter for an access token, providing consumer parameters like above as well as the previously stored request token and the PIN.
  8. From now on, send along the access token with each call to the Twitter API and everything will be fine

Twitter4j wraps the whole sequences between the client application and Twitter in its API. The first thing to do, however, is to pass it consumer key/secret. Twitter4j looks for these parameters in different places: system properties and (at the classpath root). It’s also possible to set them explicitly while configuring our Twitter client. I personally prefer to decouple it and pass them as system properties to the JVM.

// Creates the main object
Twitter twitter = new TwitterFactory().getInstance();

// Ask for a request token
RequestToken requestToken = twitter.getOAuthRequestToken();

// Store the token in session
request.getSession().setAttribute("rt", requestToken);

// Extract the authentication URL
String authUrl = requestToken.getAuthenticationURL();

// Send the Twitter authentication page to the page to create a popup from there
request.setAttribute("auth", authUrl);

This is the first part of the process and ends with the user being sent to Twitter. When he gets back, he can enter the obtained PIN.

// Read the PIN
String pin = request.getParameter("pin");

// Retrieve the request token
RequestToken requestToken = (RequestToken) request.getSession().getAttribute("rt");

// Creates the main object
Twitter twitter = new TwitterFactory().getInstance();

// Ask for an access token
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, pin);

// Store the token in session
request.getSession().setAttribute("at", accessToken);

// Remove the access token from session

// Set the access token on the twitter instance

// Now, we can ask for whatever we want!
ResponseList statuses = twitter.getUserTimeline();

Once the access token obtained, we can set it on any obtained twitter instance and we’ll be authentified on Twitter infrastructure!

Twitter4j infers that we already know about Twitter API, which was not my case. I hope those few lines of code can spare you much lost time.

To go further:

You can obtain this article sources in Maven/Eclipse format here.



Published at DZone with permission of Nicolas Frankel, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)



Maheshkumar Per... replied on Mon, 2011/03/28 - 3:24am

Normal 0 false false false MicrosoftInternetExplorer4 /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;}

Nice article. But spring-social provides generic way to interact with social sites like Facebook, Twitter, LinkedIn, etc.


Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.