How to post a Tweet in Java using Twitter REST API and Twitter4J Library

In this post, I will demonstrate how you can post a Tweet in Java  using the Twitter REST API and an open source third party twitter integration library in java called Twitter4J.
To start with you need to have an active Twitter account.


  • Log into Twitter Developer Site using your Twitter credentials.
  • Go to My Applications section and click on “Create a new application”.
  • Fill out the mandatory fields – Name, Description and Website. Accept the Terms. Fill Captcha and Submit.

twitter developer apps new application
  • Once your application is created successfully, you will be redirected to the My Applications page.
  • Click on the application you’ve just created.
  • Under the “Details” tab and “OAuth Settings”, you will find the “Consumer Key” and “Consumer Secret”. 


IMPORTANT – You should never share Consumer Key and Consumer Secret with any one.
twitter developer apps details oauth settings
  • For this example, you need a minimum of Read and Write “Access level”.
  • Click on the “Settings” tab and under “Application Type”, select the radio button option “Read and Write” or “Read, Write and Access direct messages”; which ever you like and click on the “Update this Twitter application’s settings” button at the bottom.
  • Now, go back to “Details” tab, notice that your newly set “Access level” is now reflected under the “OAuth Settings”.
  • Finally, generate your Access Token (if not already generated) by clicking the button at the bottom of “Details” tab. Do note that the “Access level” shown under the “Your access token” should match the one shown under “OAuth Settings”. Should you change your “Access level” anytime in future, you can re-generate your Access Token by clicking the button “Recreate my access token”.

So now you are all set for the coding part. You have:
  1. Consumer Key
  2. Consumer Secret
  3. Access Token
  4. Access Token Secret
For this particular example we will use Twitter REST API v1.1 and while, we can build up the necessary structure from scratch to do OAuth authentication, access token and making the raw RESTful calls all by ourselves, but we prefer to not to do this and would rather the principle of not re-inventing the wheel again. We will use a very good and easy to use Twitter Library written in Java to do the heavy lifting and save us a lot of precious time and effort.
Twitter4J is an unofficial Java library for the Twitter API. With Twitter4J, you can easily integrate your Java application with the Twitter service.
Twitter4J is:
  • 100% Pure Java - works on any Java Platform version 5 or later
  • Android platform and Google App Engine ready
  • Zero dependency : No additional jars required
  • Built-in OAuth support
  • Out-of-the-box gzip support
  • 100% Twitter API 1.1 compatible
Download Twitter4J from its official website. Unzip the downloaded folder at some location on your machine. For this example you only need the code JAR available in the lib folder.
import twitter4j.*;
import twitter4j.auth.AccessToken;   import java.io.IOException; import java.net.URL; import java.util.Arrays;   /** * This class demonstrate how you can post a Tweet in Java using the Twitter REST API and an open source third party * twitter integration library in java called Twitter4J * * User: smhumayun * Date: 7/20/13 * Time: 9:26 AM */public class TweetUsingTwitter4jExample {   public static void main(String[] args) throws IOException, TwitterException {   //Your Twitter App's Consumer Key String consumerKey = "XXXXXXXXXXXXXXXXXXXXX";   //Your Twitter App's Consumer Secret String consumerSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";   //Your Twitter Access Token String accessToken = "XXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";   //Your Twitter Access Token Secret String accessTokenSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";   //Instantiate a re-usable and thread-safe factory TwitterFactory twitterFactory = new TwitterFactory();   //Instantiate a new Twitter instance Twitter twitter = twitterFactory.getInstance();   //setup OAuth Consumer Credentials twitter.setOAuthConsumer(consumerKey, consumerSecret);   //setup OAuth Access Token twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));   //Instantiate and initialize a new twitter status update StatusUpdate statusUpdate = new StatusUpdate( //your tweet or status message "S2PTech | Java Developer | Harrison, NY | 2 Years" + " - http://s2ptech.blogspot.com/"); //attach any media, if you want to statusUpdate.setMedia( //title of media "http://s2ptech.blogspot.com/" , new URL("http://lh6.ggpht.com/-NiYLR6SkOmc/Uen_M8CpB7I/AAAAAAAAEQ8/tO7fufmK0Zg/h-1b%252520transfer%252520jobs%25255B4%25255D.png?imgmax=800").openStream());   //tweet or update status Status status = twitter.updateStatus(statusUpdate);   //response from twitter server System.out.println("status.toString() = " + status.toString()); System.out.println("status.getInReplyToScreenName() = " + status.getInReplyToScreenName()); System.out.println("status.getSource() = " + status.getSource()); System.out.println("status.getText() = " + status.getText()); System.out.println("status.getContributors() = " + Arrays.toString(status.getContributors())); System.out.println("status.getCreatedAt() = " + status.getCreatedAt()); System.out.println("status.getCurrentUserRetweetId() = " + status.getCurrentUserRetweetId()); System.out.println("status.getGeoLocation() = " + status.getGeoLocation()); System.out.println("status.getId() = " + status.getId()); System.out.println("status.getInReplyToStatusId() = " + status.getInReplyToStatusId()); System.out.println("status.getInReplyToUserId() = " + status.getInReplyToUserId()); System.out.println("status.getPlace() = " + status.getPlace()); System.out.println("status.getRetweetCount() = " + status.getRetweetCount()); System.out.println("status.getRetweetedStatus() = " + status.getRetweetedStatus()); System.out.println("status.getUser() = " + status.getUser()); System.out.println("status.getAccessLevel() = " + status.getAccessLevel()); System.out.println("status.getHashtagEntities() = " + Arrays.toString(status.getHashtagEntities())); System.out.println("status.getMediaEntities() = " + Arrays.toString(status.getMediaEntities())); if(status.getRateLimitStatus() != null) { System.out.println("status.getRateLimitStatus().getLimit() = " + status.getRateLimitStatus().getLimit()); System.out.println("status.getRateLimitStatus().getRemaining() = " + status.getRateLimitStatus().getRemaining()); System.out.println("status.getRateLimitStatus().getResetTimeInSeconds() = " + status.getRateLimitStatus().getResetTimeInSeconds()); System.out.println("status.getRateLimitStatus().getSecondsUntilReset() = " + status.getRateLimitStatus().getSecondsUntilReset()); System.out.println("status.getRateLimitStatus().getRemainingHits() = " + status.getRateLimitStatus().getRemainingHits()); } System.out.println("status.getURLEntities() = " + Arrays.toString(status.getURLEntities())); System.out.println("status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities())); }   }
Once you run the above example, you will notice an output similar to this one on your console:
status.toString() = StatusJSONImpl{createdAt=Sat Jul 20 11:47:10 EDT 2013...} status.getInReplyToScreenName() = null status.getSource() = <a href="http://s2ptech.blogspot.com" rel="nofollow">SMH's Integration App</a> status.getText() = S2PTech | Java Developer | Harrison, NY | 2 Years - http://t.co/dYnQYMKBst http://t.co/y7RJyvaaqc status.getContributors() = [] status.getCreatedAt() = Sat Jul 20 11:47:10 EDT 2013 status.getCurrentUserRetweetId() = -1 status.getGeoLocation() = null status.getId() = XXXXXXXXXXXXXXXXXX status.getInReplyToStatusId() = -1 status.getInReplyToUserId() = -1 status.getPlace() = null status.getRetweetCount() = 0 status.getRetweetedStatus() = null status.getUser() = UserJSONImpl{id=XXXXXXXX, name='S M Humayun', screenName='smhumayun'...} status.getAccessLevel() = 3 status.getHashtagEntities() = [] status.getMediaEntities() = [MediaEntityJSONImpl{...}] status.getURLEntities() = [URLEntityJSONImpl{url='http://t.co/dYnQYMKBst', expandedURL='http://s2ptech.blogspot.com/', displayURL='s2ptech.blogspot.com/'}] status.getUserMentionEntities() = []
0 Comments
Disqus
Fb Comments
Comments :

0 comments:

Post a Comment