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.












