Home > Java, Miscellaneous > How Easy to Make Your Own Twitter Client Using Java

How Easy to Make Your Own Twitter Client Using Java

Got inspired by my friend, whom built his own Twitter client for his company’s client. So, i tried to build one using Java. And im surprised that how easy to make Twitter client, of course i still use third-party API to make my job easier.

This simple client will only have 2 purposes: reading timeline and post status. Dont 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 purpose, i will create a new application that 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, dont forget the most important things in here are these Consumer and Consumer Secret key. Just say, 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 . Dont use these keys in your application, it’s useless because i will turn off the application as short as this blogging purpose done.

consumer key

And after registration step dont forget to visit Setting page and adjust setting for your application access.

tab setting

app type

Choose Read, Write and Access direct messages to get your application at full functional. you now can download additional java API for twitter, im 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>

Notes: Dont use twitter4j-appengine.jar, it will cause your application thrown to exception on authorizing process.

In my version a is 2, b is 2 and c is 4. So it would look like twitter4j-async-2.2.4 etc. After these jars being 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 it 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 “. Congratulation!

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

auth url

auth pin

update tweet

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

Now we still have a tiny problem, at this point, your program still need to open Twitter’s website and input 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.

access token

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();
    }

}

post again

tl

Now our simple Twitter application has been -could be- done, we can read and post to Twitter. Of course, many things 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 want to share it’s easy to make a Twitter client and i hope this short tutorial can help you in developing Twitter client using Java.

Happy Code All !

About these ads
Categories: Java, Miscellaneous Tags: , ,
  1. Vinay Badgoti
    6 June 2012 at 18:15

    Thank you.. !!
    Itz really a beautiful peace f code..

    • RDeJourney
      18 June 2012 at 14:21

      your welcome Vinay, pleasure is all mine :)

  2. Surya Chandra
    10 June 2012 at 17:45

    Excellent article!!! Thanks for the detailed step by step explanation. It worked like a magic.

    • RDeJourney
      18 June 2012 at 14:22

      your welcome Surya :)

  3. 9 July 2012 at 18:40

    Reblogged this on KenyanFaces.

  4. 1 August 2012 at 17:24

    good code…….but how does app knows who is posting the status if your’e not specifying the username ?

    • RDeJourney
      9 August 2012 at 10:21

      from the CONSUMER_KEY and CONSUMER_KEY_SECRET those are your authentication, so Twitter will know who you are.

  5. Suresh
    10 August 2012 at 00:23

    Couple of questions .. would be extremely happy if you can answer
    1. Looks like the communication is still between your server in which JAR is running and the twitter server ,..how does twitter client in smart phones work.. do they also do server to server communication ?

    2. Smart phone twitter clients don’t have the hazzle of entering the Pin .. how do they do that

    3. if I make it as multi-user app , I would like logged in User Name to show up in tweets instead of app name .. how do i do that ?

    Thanks for your help in advance

    -Suresh J

    • RDeJourney
      17 August 2012 at 14:53

      hi Suresh, i will try to answer your questions.
      1. i dont get it very completely, but, if im not taking your question wrong, they do the OAUTH process with the Twitter server.

      2. by Pin what do u mean? the twitter password? if this the twitter password, the twitter client will ask you to login to twitter using your mobile-browser. And after that, it will do the authentication process.

      3. you want your tweet to be like this? “sent from SureshTweet” ? if that so? you cant. Because you have to register your “Suresh Tweet” at Twitter.com first. So, shortly, this name is not dynamic

  6. Bogdan
    14 August 2012 at 18:24

    Hi, I have encountered a small problem. It seems I cannot find the Twitter in the API. I’m using twitter4j-async-2.2.6, but I tried using twitter4j-async-2.2.4 but it still does not have the Twitter class. Can you help me please?

    • Bogdan
      14 August 2012 at 20:02

      I managed to use your code, but it seems that I cannot use the modified code. I get These messages:

      401:Authentication credentials (https://dev.twitter.com/docs/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
      Relevant discussions can be found on the Internet at:
      http://www.google.co.jp/search?q=e5488403 or

      http://www.google.co.jp/search?q=0b5b09bd

      TwitterException{exceptionCode=[e5488403-0b5b09bd], statusCode=401, retryAfter=-1, rateLimitStatus=null, featureSpecificRateLimitStatus=null, version=2.2.6}
      at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:185)
      at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
      at twitter4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:93)
      at twitter4j.TwitterImpl.get(TwitterImpl.java:1711)
      at twitter4j.TwitterImpl.getHomeTimeline(TwitterImpl.java:151)

    • RDeJourney
      17 August 2012 at 14:53

      have u set your buildpath correctly? it seems you havent set your buildpath in right way

  7. Bogdan
    17 August 2012 at 15:10

    It seems this is the problem. Thanks a lot for the help and especially for the code.

    • RDeJourney
      17 August 2012 at 15:12

      your welcome…

      • Bogdan
        17 August 2012 at 15:17

        Can you help me obtain the profile image. When I try to get the profile image with twittter.getProfileImage(screenName,ImageSize) , I cannont supply the ImageSize parameter, because ImageSize is a static class from the Interface ProfileImage and is not public. Can you help me supply this parameter?

      • RDeJourney
        17 August 2012 at 15:23

        im not so sure about that, since im far away from my working laptop. And dont have the require tools to do any techical codes.q

      • Bogdan
        17 August 2012 at 15:40

        I see, I think I have an idea, I’ll try to extend ProfileImage Interface and make those fields public. Hope it will work. Thanks anyway.

  8. ciboiwaves
    4 September 2012 at 10:41

    please tell me your fave IDE.. the small and effective one.. I am new on java programing. thanks

    • RDeJourney
      4 September 2012 at 15:31

      hi, my fave would be Eclipse, not the small and light one, but it’s very rich in features and plugins.

      If you JUST want to scratch some tiny-code, how about using Textpad? or Notepad++, should be oke.

  9. Sly
    13 October 2012 at 19:14

    hi, I’m new to java, could you please help me?
    I get error at the following code:
    “07 import twitter4j.Twitter;
    08 import twitter4j.TwitterException;
    09 import twitter4j.TwitterFactory;
    10 import twitter4j.auth.AccessToken;
    11 import twitter4j.auth.RequestToken;”
    it says “The import twitter4j cannot be resolved”
    I guess I have to create a library called twitter4j first and I need to connect it to the files I’ve downloaded, but I don’t know how to do that :( (I’m using Eclipse)

    • Sly
      13 October 2012 at 20:45

      I just found out how to do that :)
      And it works!!! Omfg this is awesome! Thank you so much!!

  10. 30 October 2012 at 13:18

    There is always shown error for me like this :
    error: incompatible types
    for (Status each : list) {
    ^
    required: Status
    found: Object
    1 error

    anyone could help me please?

    • RDeJourney
      30 October 2012 at 20:58

      Hi Okta,
      Have u imported ?

      import twitter4j.Status;

  11. incy032@gmail.com
    8 December 2012 at 19:53

    Hi,
    first of all thanks for your article. It’s great.
    I have a question about how to save the home timeline of my application in xml format. Do I have to write a method using DOM or is there a better way available for replacing the System.out.println(“Sent by: @” …) method with an xml file listing all tweets available in ResponseList list?

    I would be very appreciated of any advice.

    Thanks and best regards!

    • RDeJourney
      8 December 2012 at 22:41

      Hi Incy032,
      If im not mistaken, the twitter API itself will return the XML. But the Twitter4J wrap it out into Java Bean POJO, so it would be easier to access it. Im not so sure, if twitter4j can give you back the XML, maybe you can google about it, or you can use Demarshalling library to convert it to XML.

      I dont understand about your inquiry here: is there a better way available for replacing the System.out.println(“Sent by: @” …) method with an xml file listing all tweets available in ResponseList list?. Would you mind to explain it in more detail ?

  12. incy032@gmail.com
    9 December 2012 at 04:38

    Thanks for reply. I will try to find a solution.
    Best regards.

  13. ONESHOT
    8 January 2013 at 19:16

    That was very helpful. Appreciate it.

  14. pallavi
    19 January 2013 at 01:19

    I have registered the application.And i tried to use ur code to connect to API.Its displaying the authorization URl and Input PIN here: in the console.When i open the url in the browser its not displaying any pin.

    • RDeJourney
      22 January 2013 at 23:56

      i think it will show the URL along with the PIN if you follow my steps thoroughly..

      Can you send me a screenshot?

  15. pallavi
    24 January 2013 at 01:33

    Thanks for u r reply.Now i am getting the PIN and URL.
    I Have 2 questions regarding twitter API.Please let me know the answers
    1.Can we give the website url as http://localhost:8080/SimpleServlet/Login.jsp as i am doing a POC ,i don’t have real website.
    2.If i want to authenticate the user in my app through twitter,what code i have to write ,so that user will get the URL in browser instead of console.

    Thanks

    • RDeJourney
      24 January 2013 at 01:46

      1. what URL that you want to move to your own servlet? the Authentication URL? if the Authentication URL, you cant run it from your machine, you need to run it directly from twitter website. Since it’s the substance of the OAUTH. Actually, maybe i can help you more, if you describing what do you want to do, from the scratch :)

      2. I think for that one, some services already provided it.. Though i never tried that one before, maybe you can googling about “OAUTH Provider”

  16. Mohit Verma
    1 March 2013 at 14:24

    i am not getting any PIN after hitting that link

    • RDeJourney
      7 March 2013 at 20:47

      Hi Movit,

      Ive retried my steps once again, and it seems no problem at all.. Have u retried it once again?

  17. Binay Kumar Nayak
    25 March 2013 at 20:09

    hello sir,
    it is exellent…
    I want to do another task also that is how i will do (search by username) module(it means suppose if i will type anythg in twitter search button ,the no of list name it is coming so like that i want do cn u help me)…i am doing in java… Can u tel me how i can i will proceed…

    • RDeJourney
      25 March 2013 at 20:30

      so when you type a letter, for example “Binay”, so the list contains all of the “Binay” words will appear? is that so?i think you need to use AJAX framework to do that

  18. Binay Kumar Nayak
    26 March 2013 at 18:52

    Thank u sir,

    ,,,,I will try it…..Sir i have another qs ,, actually i am dng a project (my requiremeny is login to the twitter , so i have taken a submit button , when i will click that one it will show login page of twitter ,hw u had explaind the sem way i have done that 1(it is working properly),nw what i want to do is that ,,,i have taken a text box and another 1 submit button(name is update status) so when i will click in the update status button (whatever text i have passed in that text box ) it should updated in the twitter(this is what my requirement is,,sem thg i able to do in java and JFrame. (But i am not able to do in struts using java) ) but i dnt knw it showing this error(token not found)) (before 2 and half days i am trying ..still i didnt get) .. can u help me sir or can anyone help me…

    type Exception report

    message java.lang.IllegalStateException: No Token available.

    description The server encountered an internal error that prevented it from fulfilling this request.

    exception

    javax.servlet.ServletException: java.lang.IllegalStateException: No Token available.
    org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:286)
    org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
    org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

    Thank u.
    Regards
    Binay Kumar Nayak

    • RDeJourney
      27 March 2013 at 09:55

      hi Binay,
      Can u send me screenshots of your UI, struts or anything, since i have not enough information and im afraid i will be misleading you.

  19. 27 March 2013 at 01:47

    Oh my goodness! Awesome article dude! Thank you so much, However I am encountering problems with your RSS.
    I don’t understand why I cannot subscribe to it. Is there anybody having similar RSS issues? Anyone that knows the solution will you kindly respond? Thanx!!

  20. Binay Kumar Nayak
    27 March 2013 at 12:28

    Hi sir,
    Thnak u so much sir for ur quick reply,
    How i will send u ,can u give me ur mail id(if u dnt have any pbm),really for this pbm i am struggling alot…

    Thank u.
    Regards
    Biany Kumar Nayak

    • RDeJourney
      27 March 2013 at 12:34

      you can it into ronald.daniel@hp.com , i’m a bit busy now, but i will try my best to take a look of this

  21. Binay Kumar Nayak
    27 March 2013 at 13:38

    Hi sir.
    I have sent u all the files …plz chk it…

    Thank u.
    Regards
    Binay Kmar Nayak

  22. Binay Kumar Nayak
    29 March 2013 at 18:24

    Hi Sir ,
    Last time i asked a qs how i will do the module(search by username) ..u told 2 use Ajax..
    k fin this is…can u give some suggestions ,i want 2 do is search by username ,,suppose i will write any name then if i will press enter key or submit button(search) then it should display the specified user names tweet, his image …(how it is coming in twitter ) not exact but like that i want to do like that…. how i will do that,,,,i am using java with struts …can u give some idea how to proceed…

    Thank u.
    Regards
    Binay Kumar Nayak

    • RDeJourney
      29 March 2013 at 18:53

      i think twitter has its own API for that, have u gone through their website documentation API?

  23. Binay Kumar Nayak
    29 March 2013 at 18:59

    Hi sir,

    http://mobile.tutsplus.com/tutorials/android/build-a-twitter-search-app-project-setup/

    http://mobile.tutsplus.com/tutorials/android/build-a-twitter-search-app-fetch-parse-the-twitter-json-feed/

    In these two sites(exact things wht i want 2 do they have done in android) they have explained nicely in android….why i have written these two sites bcoz i want to do lik that in java …..can u give some idea through which i can proceed…

    Thank u.
    Regards
    Binay Kumar Nayak

    • RDeJourney
      29 March 2013 at 19:06

      for that one, i think twitter has API, you need to dig through their documentation, https://dev.twitter.com/

  24. Binay Kumar Nayak
    29 March 2013 at 19:07

    Hi sir,
    yah i am using twitter api,,,i was telling u abt the lgoin page and update status and all…
    for that i used twitter api …
    ….

    Thank u.
    Regards
    Bin ay Kaumar Nayak

    • RDeJourney
      30 March 2013 at 19:24

      which api that u used?

  25. 11 July 2013 at 22:27

    It returns “incompatible types” for “list” (which is defined in the line above) in line 36… How to fix that? :o

  26. priya
    12 July 2013 at 02:54

    Hi,
    Please help me..I am geeing the following error.

    410:
    Relevant discussions can be on the Internet at:
    http://www.google.co.jp/search?q=48e6de24 or

    http://www.google.co.jp/search?q=00cc4504

    TwitterException{exceptionCode=[48e6de24-00cc4504], statusCode=410, retryAfter=0, rateLimitStatus=null, version=2.2.0}
    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:189)
    at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
    at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102)
    at twitter4j.TwitterImpl.updateStatus(TwitterImpl.java:446)
    at com.gov.tweet.Tweet.postToTwitter(Tweet.java:66)
    at com.gov.tweet.Tweet.main(Tweet.java:18)

    • RDeJourney
      26 July 2013 at 15:07

      hi Priya, so sorry, but i couldnt recreated that error. So i couldnt find the solution as per now

  1. 12 October 2011 at 22:05

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 726 other followers

%d bloggers like this: