Ronald Djunaedi

About Ronald Djunaedi

Ronald is a senior Java Developer, specialization in J2EE Programming and its technologies and frameworks. Been a trainer for a while, specialization in training subjects: Java Fundamentals, OOP and J2EE.

Java Twitter client with Twitter4j

Got inspired by my friend, who built his own Twitter client for his company’s client. So, I tried to build one using Java. And I’m surprised at how easy is to make a Twitter client, of course I still use a third-party API to make my job easier.

This simple client will only have 2 purposes: reading timeline and post status. Don’t worry, you can expand this application later, it’s simple and easy once you have your app got authorized by Twitter.

First of all, you have to go to official Twitter Developer Registration at https://dev.twitter.com/apps/new and register your application detail there. For this blog, I will create a new application that is called “Namex Tweet for Demo“. It’s simple, just fill in some required data and voila it’s done in seconds.

After you passed this registration step, don’t forget the most important things in here are these Consumer and Consumer Secret key. In short, it’s a signature to let Twitter knows your application. These things will be hardcoded at your application.

In here, my Consumer key is DXjHgk9BHPmekJ2r7OnDg and my Consumer Secret key is u36Xuak99M9tf9Jfms8syFjf1k2LLH9XKJTrAbftE0. Don’t use these keys in your application, it’s useless because I will turn off the application as short as this blog post is done.

And after the registration step don’t forget to visit the Settings page and adjust the setting for your application access.

Choose “Read, Write and Access direct messages” to get your application the full functionality.

You can now download the additional Java API for twitter, I’m using Twitter4J. Here, you have to download several jars,

  • twitter4j-async-a.b.c.
  • twitter4j-core-a.b.c.
  • twitter4j-media-support-a.b.c.
  • twitter4j-stream-a.b.c.

Note:Don’t use the twitter4j-appengine.jar, it will cause your application to throw an exception on authorizing process.

In my example a is 2, b is 2 and c is 4. So it would look like twitter4j-async-2.2.4 etc. After these jars are downloaded at your machine, our downloading job has not done yet. We still have to download Apache Commons Codec as Twitter4J dependencies. After all of the jars downloaded, now we can start to code. Open your fave IDE and start with me.

package com.namex.tweet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

public class NamexTweet {
    private final static String CONSUMER_KEY = "DXjHgk9BHPmekJ2r7OnDg";
    private final static String CONSUMER_KEY_SECRET = "u36Xuak99M9tf9Jfms8syFjf1k2LLH9XKJTrAbftE0";

    public void start() throws TwitterException, IOException {

 Twitter twitter = new TwitterFactory().getInstance();
 twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
 RequestToken requestToken = twitter.getOAuthRequestToken();
 System.out.println("Authorization URL: \n"
  + requestToken.getAuthorizationURL());

 AccessToken accessToken = null;

 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 while (null == accessToken) {
     try {
  System.out.print("Input PIN here: ");
  String pin = br.readLine();

  accessToken = twitter.getOAuthAccessToken(requestToken, pin);

     } catch (TwitterException te) {

  System.out.println("Failed to get access token, caused by: "
   + te.getMessage());

  System.out.println("Retry input PIN");

     }
 }

 System.out.println("Access Token: " + accessToken.getToken());
 System.out.println("Access Token Secret: "
  + accessToken.getTokenSecret());

 twitter.updateStatus("hi.. im updating this using Namex Tweet for Demo");

    }

    public static void main(String[] args) throws Exception {
 new NamexTweet().start();// run the Twitter client
    }
}

Compile and run the code, it will create permission for “Namex Tweet for Demo” to be linked with your Twitter account. Just open the “Authorization URL” shown at the screen and input the PIN shown by the website.

Your application will send back the pin to Twitter, if it’s match your account will be linked with this new application and you can see you just posted a new status using “Namex Tweet for Demo “. Congratulations!

Note: Authorization URL and PIN will generated differently each time it’s run.

In here you can see, we don’t give the username and password of Twitter account but we can use our account within the application. Yeah it’s possible because of OAuth. It “transformed” password-input-process to sending-receive-token. So don’t worry, a third-party Twitter client application can’t read and store no password of your Twitter account. It’s simple, it’s safer and prevents password thieving.

Now we still have a tiny problem, at this point, your program still needs to open Twitter’s website and give the pin back to the application. So, maybe you are asking, on the cloud, do I need this annoying authorization on the future? Well, gladly the answer is NO. At the time your app being authorized by Twitter, you have no use to re-authorize it again — with a simple note you have to save the Access Token and Secret Access Token .

What the hell is that, how could I get that. Well, you have it already, see the image below, I put it in a big red rectangle so it will be more eye-catchy. In here, our token is and our secret token is. These 2 tokens have to be saved somewhere, you can choose your own method to save it: Persistence, CSV, DBMS, etc. It’s all up to you.

So, i saved the tokens! How do i reuse it? It’s simple, see below code. It’s how to use your tokens, so you wont have the re-authorization process again. Try to post and read your timeline now.

package com.namex.tweet;

import java.io.IOException;

import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;

public class NamexTweet {
 
    private final static String CONSUMER_KEY = "DXjHgk9BHPmekJ2r7OnDg";
    private final static String CONSUMER_KEY_SECRET =
     "u36Xuak99M9tf9Jfms8syFjf1k2LLH9XKJTrAbftE0";

    public void start() throws TwitterException, IOException {

 Twitter twitter = new TwitterFactory().getInstance();
 twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);

 // here's the difference
 String accessToken = getSavedAccessToken();
 String accessTokenSecret = getSavedAccessTokenSecret();
 AccessToken oathAccessToken = new AccessToken(accessToken,
  accessTokenSecret);

 twitter.setOAuthAccessToken(oathAccessToken);
 // end of difference

 twitter.updateStatus("Hi, im updating status again from Namex Tweet for Demo");

 System.out.println("\nMy Timeline:");

 // I'm reading your timeline
 ResponseList list = twitter.getHomeTimeline();
 for (Status each : list) {

     System.out.println("Sent by: @" + each.getUser().getScreenName()
      + " - " + each.getUser().getName() + "\n" + each.getText()
      + "\n");
 }

    }

    private String getSavedAccessTokenSecret() {
 // consider this is method to get your previously saved Access Token
 // Secret
 return "oC8tImRFL6i8TuRkTEaIcWsF8oY4SL5iTGNkG9O0Q";
    }

    private String getSavedAccessToken() {
 // consider this is method to get your previously saved Access Token
 return "102333999-M4W1Jtp8y8QY8RH7OxGWbM5Len5xOeeTUuG7QfcY";
    }

    public static void main(String[] args) throws Exception {
 new NamexTweet().start();
    }

}

Now our simple Twitter application has been -could be- done, we can read and post to Twitter. Of course, many things are still on the task list if you want to make it professionally and -perhaps- sell it. A nice UI, reading and sending Direct Message, Searching Users, Follow and Unfollow. I put these jobs on your shoulder, cause i just wanted to share that it’s easy to make a Twitter client and I hope this short tutorial can help you in developing a Twitter client using Java.

Reference: How Easy to Make Your Own Twitter Client Using Java from our JCG partner Ronald at Naming Exception Blog.

Related Articles :
Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

11 Responses to "Java Twitter client with Twitter4j"

  1. wathmal says:

    wow ,, this is really awesome n i really wanted this tutorial,,, thank u very much,,,,,,,,,

  2. harshad says:

    where can I get the code for A nice UI, reading and sending Direct Message, Searching Users, Follow and Unfollow. pls tell me and help me…

  3. 0xAntia says:

    hi

    if I wanted to let the end user decide what user and password to enter, and then use the app, how should I do? What should I use instead of the various access token and consumer key?

    thank you!

  4. Christiano says:

    Hi,

    this is very helpful! However, my question is what happens when the current access token expires?! Do you need to go again through the authorization procedure or is there any way around to automate this process instead of having the user to go and get a pin??

    Many thanks.

  5. Vinay says:

    Hello Ronald,

    Thanks a lot for the code. I have a question. I was able to read all the tweets from my user account but i want to retrieve tweets from other users. How to do this? Your help would be appreciated.

    -Thank you,
    Vinay

  6. navin says:

    Hey Thanks Ronald,
    Thanks a lot for the code. Now I can start on my project. It was really helpful.

  7. I’ve saved the tokens… but I can’t reuse them.. everytime I try it gives me “Invalid/Expired token”.

    To the surprise, it used to work before, but don’t work anymore (don’t know exactly when it stopped).

    Can you please make an example using the latest twitter4j and present that here.

    Regards
    Nitin

  8. vinod sharma says:

    hi
    very helpful tutorial indeed but even though i followed you to every step still need to generate the pin every time i run it .

  9. bindya says:

    Hi I am getting an error when i am trying to call this class in jsp.

    javax.servlet.ServletException: java.lang.NoClassDefFoundError: javax/crypto/Mac

    Can anyone help me resolve it?

  10. jitendra says:

    how to get pin ??

Leave a Reply


2 + nine =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books