Core Java

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 :

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. Has been involved actively in numerous IT Software Development Projects with multiple companies and clients.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

19 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
wathmal
wathmal
12 years ago

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

harshad
harshad
12 years ago

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…

0xAntia
0xAntia
11 years ago

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!

Christiano
Christiano
11 years ago

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.

Vinay
Vinay
11 years ago

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

navin
navin
11 years ago

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

Nitin Surana
11 years ago

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

vinod sharma
vinod sharma
11 years ago

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 .

bindya
bindya
10 years ago

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?

jitendra
jitendra
10 years ago

how to get pin ??

vishwa
vishwa
10 years ago

thanks

ganesh
ganesh
9 years ago

hi

is there any way to get Popular Tweets for the day in the world using this twitter4j

Rajesh Kumar Sahanee
9 years ago

Nice tutorial Ronald, It helped me a lot in my own twitter application development.

photo prueba
photo prueba
9 years ago

Hello! tanks for you post.
Do yo known how I can unpload a image from my java app?

Nitish
Nitish
8 years ago

Could u plzz tell me how can i get the location of an user

Daniel
Daniel
7 years ago

hi ronald , thank you very much |!

Mohan
Mohan
7 years ago

Hay Great article, Thanks..
Please update URL for creating twitter app.

https://apps.twitter.com/app/new

Eppromripper
Eppromripper
3 years ago

Hello i get error in line 38 “incompatible types, object cannot be converted to status”

what could be the problem. thanks

Back to top button