Posting To Twitter

Many web applications need to connect to and integrate with Twitter. In Java, the best and most widely-used library is twitter4j. The following code snippet shows how to connect to Twitter and post a tweet.

Oauth_consumer_keyoauth_consumer_secretoauth_access_token, and oauth_access_token_secret are the Twitter OAuth authentication keys. You can generate those keys by going to Twitter’s developer site and creating an application plus access tokens. The string tweet_text is the text to post to Twitter. If any problems occur while posting to Twitter, a TwitterException will be thrown.

ConfigurationBuilder config = new ConfigurationBuilder();
config.setDebugEnabled(true);
config.setOAuthConsumerKey(oauth_consumer_key);
config.setOAuthConsumerSecret(oauth_consumer_secret);
config.setOAuthAccessToken(oauth_access_token);
config.setOAuthAccessTokenSecret(oauth_access_token_secret);
Twitter twitter = (new TwitterFactory(config.build())).getInstance();
try {
    //Post to Twitter.
    twitter.updateStatus(tweet_text);
}
catch (TwitterException e) {
    //error posting to Twitter
}