Thursday, March 8, 2012

Wanna Tweet on your twitter page using JAVA API...?? Here's the way..

  • Tweet on your twitter page....
  1. First download Twitter4j java library from Twitter4j website    
  2. Since, I'm using eclipse IDE, downloaded twitter4j zip file and selected its lib file in the eclipse project's build path.(lib file is twitter4j-core.2.2.5.jar)
  3. A sample program to post on twitter is mentioned at the bottom of the post...
  4. THE MOST IMPORTANT STEP is this i.e. to get ur consumer key, consumer secret, access token and access token secret which needs to be entered in the java program.
To get those you need to follow the following steps
  • You need to have twitter account(sign up fast)...
  •  go to https://dev.twitter.com/apps 
  • and click on create new application
  • Enter app name, description, URL(any website of urs example can be ur blog) and finally agree for the agreement and click the button to proceed to next page
  • In this page you will find ur two keys(consumer key and consumer secret) you need to enter in your program...at the bottom u can find create ur access key, click on that with which u will get ur access token and access token secret but these keys are valid on for read access i.e. to GET data
  • To POST data(read and write to ur twitter) go to settings tab and set application type to Read, Write and Access direct messages and save it, ur new keys will be generated.
  • Now enter all ur keys in the program below and run the program with ur own message :)
  • Ur msg will be finally seen in ur own twitter page...
import twitter4j.*;
import twitter4j.conf.*;

public class TestTw {
public static void main(String args[]) throws TwitterException{
    // The factory instance is re-useable and thread safe.
   
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true)
      .setOAuthConsumerKey(<ur consumer key>)
      .setOAuthConsumerSecret(<ur consumer secret>)
      .setOAuthAccessToken(<ur access token>)
      .setOAuthAccessTokenSecret(<ur access token secret>);
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
   
    Status status = twitter.updateStatus("This is the test message using twitter4j API");
    System.out.println("Successfully updated the status to [" + status.getText() + "].");
    }
   
}  

No comments:

Post a Comment