Integrating Java Application with Twitter

13 / Jul / 2010 by Anshul Sharma 2 comments

These are few basic steps which will help you to integrate your java application with twitter using twitter4j.

Twitter4J is a Java library for the Twitter API.
With Twitter4J, you can easily integrate your Java application with the Twitter.

Steps :

1) Register your application at http://twitter.com/apps
2) Twitter will return Consumer Key and Consumer Secret for your application.
3) Download the twitter4j jar and place that jar file in the classpath.
4) Create a login action:

// Login Action
Twitter twitter = new Twitter();
twitter.setOAuthConsumer(ConsumerKey,ConsumerSecret);
RequestToken requestToken = twitter.getOAuthRequestToken('callbackurl');
String authUrl = requestToken.getAuthorizationURL(); 
session.setAttribute("request-token",  requestToken);
redirect(url: authUrl);
 

5) Create a callback action .

///  Call back action: Where the twitter will redirect after successfull authentication.
RequestToken requestToken = (RequestToken) session.getAttribute("request-token");
String verifier = request.getParameter("oauth_verifier")
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken,verifier)
 

6) Persist the access token and token secret for future use. (accessToken.token ,accessToken.tokenSecret). The access token never expire until the user explicitly rejects the application from his settings.

7) Now whenever you want to create the twitter client , just follow the steps below:

             
Twitter twitter = new Twitter()
twitter.setOAuthConsumer(ConsumerKey, ConsumerSecret)
twitter.setOAuthAccessToken(token, secretToken)  //  token, secretToken which you have persisted in step 6.
// For Example: to search someone on twitter.
List users = twitter.searchUsers(name, 1)
 

Hope this helped!

Cheers!

Anshul Sharma

FOUND THIS USEFUL? SHARE IT

comments (2)

  1. John

    hello dear

    I am getting null error while trying to access the ACCESSTOKEN? I get the value of requestToken and Verifier but whey try the method call –
    AccessToken accessToken = twitter.getOAuthAccessToken(requestToken,verifier)

    It throws the error. Please help if possible.

    Thanks
    John

    Reply
  2. Letha

    I don’t usually answer to articles but I will in this situation. Intriguing article. Where did you got all the facts from? Regardless thank you for this excellent post! Respectfully, Letha.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *