Java application to integrate Twitter-api



Twitter a microblogging service is getting more and more popular these  days. A lot of developers are involved to develop applications on its  API.
Two weeks ago I click with a very basic idea and being as a matter of learning I started working on it. I have finished more than 80% of the work. I deployed the application on Google App Engine (I hope you are familiar with it).
I used Twitter4J lib a Java wrapper for Twitter API.
If you are also interested in Twitter based app development in Jave, then this tutorial will be helpful for you. Feel free to add comments at the end of the post, I will love to reply.

Things you require for development

Things you need to know before you start

-----------------------------------------------------------------------------------------------------------------------
Desktop java Application for integrating twitter-api


System Requirement: Jdk 1.5 or later OR eclipse(You can run simple java program in eclipse Id also) /Windows XP
Jar:
(include in library to these files)

Oauth authentication
You should know Oauth basics and its terminologies. You can little google on it or read this FAQs
Register an App with Twitter
You need to register an application on this URL: http://twitter.com/oauth. Please take care of two things. The call back URL will not be your localhost URL. It should be a valid web address. And while choosing Default Access Type, if your application need to do changes or send tweets then you should choose Read & Write otherwise/if you just want to do readonly operations then leave Read-only checked.

Here you will get following information:


  • zi3gej7WevZQ7k85NILQ     (Must be different for you)

  • 6DbinNeoSpQvUP3gI8pwq3CFY7VVRs8SsWmkA31Oxoc  (Must be different for you)

  • http://twitter.com/oauth/request_token

  • http://twitter.com/oauth/access_token

  • http://twitter.com/oauth/authorize

Steps:
  1. When your users want to access Twitter through your application for the first time, you should display some kind of notification which indicates that an authentication process is about to start
  2. Call OAuthProvider.retrieveRequestToken(callback) on the OAuthProvider. If your application can receive callbacks via URLs, you can be informed about successful authorization by providing a callback URL here. If you cannot receive callbacks (e.g. because you're developing a desktop application), then you must pass "oob" here (for "out of band").
  3. On method return, you have to send the user to the URL returned by it. The user now must grant your application access to Twitter - this step is out of the reach of your application, because it happens in the Web browser.
  4. Call OAuthProvider.retrieveAccessToken() with the PIN code generated by Twitter in the previous step. If your interaction style is out-of-band, then you must ask the user to enter this value somewhere, since there is no way to get it programatically. If however you defined a callback URL before, then the PIN code will be passed to your application automatically with that callback as an "oauth_verifier" parameter.
  5. On method return, call OAuthConsumer.getToken() and OAuthConsumer.getTokenSecret(), associate them with the user who triggered the authorization procedure, and store them away safely.
  6. Any OAuthConsumer configured with these values can now sign HTTP requests in order to access protected resources on Twitter on behalf of that user.
--------------------------------------------------------------------------------
Java Code: Main.java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthConsumer;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.signature.SignatureMethod;



import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import winterwell.jtwitter.*;

public class Main {

    public static void main(String[] args) throws Exception {

       
 String consumerKey="zi3gej7WevZQ7k85NILQ";    //Use your own key
String consumerSecret="6DbinNeoSpQvUP3gI8pwq3CFY7VVRs8SsWmkA31Oxoc"; //use your //own

        OAuthConsumer consumer = new DefaultOAuthConsumer(consumerKey,consumerSecret,SignatureMethod.HMAC_SHA1);

        OAuthProvider provider = new DefaultOAuthProvider(consumer,
                "https://api.twitter.com/oauth/request_token",
                "https://api.twitter.com/oauth/access_token",
                "https://api.twitter.com/oauth/authorize");

        System.out.println("Fetching request token from Twitter...");

        // we do not support callbacks, thus pass OOB
        String authUrl = provider.retrieveRequestToken(OAuth.OUT_OF_BAND);

        System.out.println("Request token: " + consumer.getToken());
        System.out.println("Token secret: " + consumer.getTokenSecret());

        System.out.println("Now visit:\n" + authUrl
                + "\n... and grant this app authorization");
        System.out.println("Enter the PIN code and hit ENTER when you're done:");

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String pin = br.readLine();

        System.out.println("Fetching access token from Twitter...");

        provider.retrieveAccessToken(pin);

        System.out.println("Access token: " + consumer.getToken());
        System.out.println("Token secret: " + consumer.getTokenSecret());

        URL url = new URL("http://twitter.com/statuses/mentions.xml");
        HttpURLConnection request = (HttpURLConnection) url.openConnection();

        consumer.sign(request);

        System.out.println("Sending request to Twitter...");
        request.connect();

        System.out.println("Response: " + request.getResponseCode() + " "
                + request.getResponseMessage());

       
        //-------------Now added later for update in twitter account
        System.out.println("Access token:again:" + consumer.getToken());
        System.out.println("Token secret:again: " + consumer.getTokenSecret());
       
        TwitterFactory factory = new TwitterFactory();
        AccessToken accessToken = new AccessToken(consumer.getToken(), consumer.getTokenSecret());
        Twitter twitter=factory.getOAuthAuthorizedInstance(consumerKey,consumerSecret, accessToken);
        Status status = twitter.updateStatus("Hello! I am from local console");                                                                                                                           

        System.out.println("Successfully updated the status -----See Your twitter account::");
        System.exit(0);

        //-----------------------------------------------------------
    }
}



--------------------------------------------------------------------------------
Fetching request token from Twitter...
Request token: g1re4iYfknOYMB62JZkddjwhCfvfn4WPdZrzgscMOA
Token secret: wKStK0dmhPcuFxBki3imJv7yVNXgRndmW4LSmuCg
Now visit:

http://twitter.com/oauth/authorize?oauth_token=g1re4iYfknOYMB62JZkddjwhCfvfn4WPdZrzgscMOA ... and grant this app authorization
Enter the PIN code and hit ENTER when you're done:
xxxxxxx
Fetching access token from Twitter...
Access token: 14418463-Xt70aZ8b2jz19MzY7JnQJ6HglPh0Hc5p939gLH5YI
Token secret: TkG689FOx7amgdX2ta6epE5MYsmZxVuO9ith7FtJrs
Sending request to Twitter...
Response: 200 OK
 Access token:again:14418463-Xt70aZ8b2jz19MzY7JnQJ6HglPh0Hc5p939gLH5YI
 Token secret:again:
TkG689FOx7amgdX2ta6epE5MYsmZxVuO9ith7FtJrs
---------------------------------------------------------------------------------

Note: Just see the console and copy the URL after Now Visit: and paste this URL on browser to get a PIN..(It will allow you on twitter site after valid login and then give you a PIN)

Now enter this PIN in Console and enter...see rest of the process....

Now next time you don't need to run Main Class each time...Just save the Access Token and Token Secret along with Consumer Key and ConsumerSecret at somewhere..each time when you send new request to write some tweet, you need these three lines every time...
TwitterFactory factory = new TwitterFactory();
        AccessToken accessToken = new AccessToken(consumer.getToken(), consumer.getTokenSecret());
        Twitter twitter=factory.getOAuthAuthorizedInstance(consumerKey,consumerSecret, accessToken);


And then you can write new tweets from your program.....

See next example.............
----------------------------------------------------------------------------------------------------------------
GetFriendsTimeLine.java

 import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.http.AccessToken;

import java.util.List;


public class GetFriendsTimeline {

    public static void main(String[] args) {
        String consumerToken="150227733-iGvZdWhbIFiieaXN9P5NcAeLWZCnH5mEtoY6QS2E";
        String consumerSecret="HhpddehDDdMCFahO95udhA74YW9DHNfAZQkX8lUucY";
      
        try {
            // gets Twitter instance with default credentials
            System.out.println("------Search for Friends-----");
            TwitterFactory factory = new TwitterFactory();
            AccessToken accessToken = new AccessToken(consumerToken, consumerSecret);
            Twitter twitter=factory.getOAuthAuthorizedInstance("zi3gej7WevZQ7k85NILQ","6DbinNeoSpQvUP3gI8pwq3CFY7VVRs8SsWmkA31Oxoc", accessToken);
           
            User user = twitter.verifyCredentials();
            List statuses = twitter.getHomeTimeline();
            System.out.println("Showing @" + user.getScreenName() + "'s home timeline.");
            for (Status status : statuses) {
                System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
            }
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to get timeline: " + te.getMessage());
            System.exit(-1);
        }
    }
}

 ----------------------------------------------------------------------------------------------------------------------

Out put----------------

Showing @youdhveerpanwar's home timeline.
@SrBachchan - T 268 -Abhishek shoots for 'Players' not 'Game' as rightly pointed out from my Blog .. thank you .. love and Good night !!
@SrBachchan - T 268 - With due respect I present to you my Blog for the day .. I mean every word of it ..

Bhopal, Madhya (cont) http://tl.gd/8jrjke
@SrBachchan - T 268 -I have RT AmareshRath, comment just now .. and i intend to show this to my director tomorrow .. he may be interested to know this ..!
@SrBachchan - RT @AmareshRath: @SrBachchan saahab! hamaare desh mein aarakshan mein aarak'shit' zyadatar woh log hain jinko uski darkaar nahi.
@SrBachchan - T 268 -Another comments, and rightly so, 'reservation comes from segregation.. why segregation ?' Exactly ! We are all equal, all human !
@SrBachchan - T 268 - Someone asked me 'is not this a controversial topic' .. yes it is my friend .. much like most other topics in the world ..
@SrBachchan - T 268 -There has been much debate on the topic .. Prakash Jha wishes to address them all in his film ..its a student community film ..
@SrBachchan - T 268 -NewZealand 7.5 hrs ahead and way past midnight into 5 th feb, Abhisheks Birthaday .. wished him .. will wish again when he gets up
@SrBachchan - T 268 -Many asking what 'Aarakshan' means and is about .. It means 'reservation' and is based on the education system and reservations ..
@SrBachchan - T 268 -Back from shoot of 'Aarakshan' .. somewhat relaxed day .. but tomorrow, most trying and tense and tough .. enjoying hospitality of Bp
@SrBachchan - T 267 - ..and now by very popular demand i disappear to write my blog .. and then to retire for another grueling tomorrow .. Peace and love
@SrBachchan - T 267 -Soooo ... !! So many responded and so very intelligently too .. I am so impressed and happy with my TwFmXt, on the privacy article !
@SrBachchan - T 267 -Read an article where the tilt is that in the age of Twitter, do celebrities deserve their right to privacy .. Hmmm !! Any comments ?
@SrBachchan - T 267 -Depressing to see beautiful Cairo in turmoil ..remember nostalgically my visit there and the enormous attention and love they gave me
@SrBachchan - T 267 -And so to end another intense day at shoot ! Credit to the students of Oriental College for their magnificent discipline and love ..
@virendersehwag - Getting ready for world cup
@youdhveerpanwar - Hello! This is a tweet from desktop application created by Youdhveer at ebuisnessware
@virendersehwag - Getting ready for world
@youdhveerpanwar - Hello! I am from local console
@virendersehwag - Watch me in conversation with @gauravcnnibn at 730pm on the world cup
---------------------------------------------------------------------------------------------------

For any query mail us at info@knowledgeserve.in or post us at facebook: knowledgeserve@Facebook
Also you can Follow us at Knowledgeserve@twitter

Popular posts from this blog

Can not connect to git using ssh (Permissions 0644 for '/root/.ssh/id_rsa' are too open.

Upload file on Google cloud storage using Java servlet on google app engine

Session timeout interceptor in struts 2