Retweet a tweet using Twitter4j

24 / Sep / 2012 by Vishal Sahu 2 comments

Hi,

In one of my grails project, i worked on integrating twitter API with the grails application. The requirement is such that we need to display all of the tweets to any user in our application and provide the basic functionality such as reply, retweet, favorite, send direct message etc using the API calls. I used Twitter4j (a java wrapper for twitter API calls), to make API calls.


In the previous blog, we saw how to mark any tweet as ‘Favorite’ using Twitter4j. In this blog we will see how to Retweet any particular tweet using the same library


For making any twitter API calls we need to have twitter account access_token and access_secret, which we obtains after authorizing/connecting twitter account with the application as mentioned in this blog.


Pre-Requirements:-

       String consumerKey = CONSUMER_KEY // key obtained after registering app.
       String consumerSecret =CONSUMER_SECRET // secret key obtained from the registered app.
       String twitterToken = USER_TWITTER_TOKEN
       // access_token received by authentication user's twitter account
       String twitterSecret= USER_TWITTER_SECRET
        // access_secret obtained by authentication user's twitter account
       Long tweetId = // messageId of the tweet to be retweeted


Code to Retweet a Tweet:-


       TwitterFactory factory = new TwitterFactory()
        Twitter twitter = factory.getInstance()
        twitter.setOAuthConsumer(consumerKey, consumerSecret)
        AccessToken accessToken = new AccessToken(twitterToken, twitterSecret)
        twitter.setOAuthAccessToken(accessToken)
        twitter.retweetStatus(tweetId)
    }

So, the above code will create a Retweet for that tweet.
This worked for me.
Hope it helps.


Other Blogs:-

Send Direct Message using Twitter4j
Mark Tweet as Favorite using Twitter4j
Reply to a tweet using Twitter4j
Post status update using Twitter4j


Cheers!!!
Vishal Sahu
vishal@intelligrape.com

FOUND THIS USEFUL? SHARE IT

comments (2)

Leave a comment -