Checking For A Twitter Follow

This brief code example checks to see whether user_to_check (a Twitter username as a String) is following the Twitter account twitter_username. The boolean is_user_following will be true if there is a follow.

The twitter object represents a twitter4j.Twitter class preconfigured with authentication details.

Relationship to_other_user = twitter.showFriendship(twitter_username, user_to_check);
boolean is_user_following = to_other_user.isTargetFollowingSource();

Geolocating A Tweet In Java

Here’s a demonstration of how to use the twitter4j library to post a tweet and set a location from where it was posted.

This example requires a twitter4j.twitter object (the twitter variable) to be preconfigured with authentication tokens. Replace the text Orlando, FL with a string describing the user’s location, and the GPS coordinates with your user’s coordinates.

    StatusUpdate status = new StatusUpdate(tweet_text);
     * We'll add location information for this tweet. 
     * Here, we tell Twitter that this tweet was made from Orlando, FL.
     * The GPS coordinates here are for Walt Disney's Hollywood Studios theme park.
    status.placeId("Orlando, FL");
    GeoLocation geolocate = new GeoLocation(28.355269, -81.559390);
    //And finally, post this tweet.
    try {
    catch (TwitterException e) {
        System.err.println("Problem accessing Twitter. Exception message: " + e.getMessage());

Remember the appropriate import:

import twitter4j.*;

Retweeting In Java

Earlier I posted examples of how to log into Twitter and post a tweet using the twitter4j library. Now here’s a function demonstrating how to retweet a post.

This function is entirely self-contained; all it requires is a global variable twitter, which represents a twitter4j.Twitter object preconfigured with the proper authentication details.

public void doRetweet() {
     * To demonstrate retweeting, we'll search Twitter for all tweets that contain 
     * the phrase "mail not working" (including quotation marks). We'll then select 
     * a random tweet, and retweet it into our stream.
    try {
        //Search for tweets, then pull out a list of those tweets.
        //A Status is how twitter4j refers to an individual tweet.
        twitter4j.Query q = new twitter4j.Query("\"mail not working\"");
        List<Status> results =;
        //Randomly select a tweet
        Random generator = new Random();
        int pick = generator.nextInt(results.size());
        Status status_to_retweet = results.get(pick);
        //Log the tweet we're retweeting
        System.out.println("Now retweeting: " + status_to_retweet.toString());
        //And finally retweet that tweet
        long status_id = status_to_retweet.getId();
    catch (TwitterException e) {
        System.err.println("A TwitterException has occurred while attempting to retweet. Exception message: " + e.getMessage());
}//end function

Searching Twitter

Many web applications integrate Twitter into their pages to display realtime news and thoughts. Here’s a code snippet showing how to search Twitter using the twitter4j library.

Twitter’s search API doesn’t return all search results at once; instead it returns “pages” of results, with each page containing 100 tweets matching the search criteria. The following code snippet runs through many pages of search results using a while loop, so it may take some time to process. Run it within a backend if you’re searching for a particularly popular phrase or doing heavy processing on each tweet.

The variable twitter represents a twitter4j.Twitter object, and status represents a single tweet. You can extract tweet information from that object; for example status.getText() would return the text of the tweet. Edit the string “google app engine” to whatever text you’re searching Twitter for.

twitter4j.Query twitter_query = new twitter4j.Query("google app engine");
//This while loop runs through each page of the returned 
//tweets. One page of results (100 tweets) is processed 
//per loop.
while (twitter_query != null) {
    //A list of the returned tweets, representing 1 page (100 tweets).
    QueryResult twitter_results =;
    //Run through this page of results and access each returned tweet.
    for (Status status : twitter_results.getTweets()) {
        //Do something with the status object.
    //Retrieves a Query representing the next page of results.
    twitter_query = twitter_results.nextQuery();
}//end while loop running through pages of returned results.


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();
Twitter twitter = (new TwitterFactory(;
try {
    //Post to Twitter.
catch (TwitterException e) {
    //error posting to Twitter

Creating Twitter Access Credentials

Integrating Twitter access to your application is fairly simple. But before you write a single line of code, you need OAuth access credentials to log into Twitter. Here’s how to get those credentials.

First, go to You’ll see the following screen:

Click on Create Application, then fill in the application details boxes in the next screen:

Scroll all the way down and click the button marked Create Application.

After that, go to the Settings tab of your new application:

Go down to the Application Type section:

Click on the “Read, Write and Access direct messages” option, and save your settings.

Go back to the details tab:

Scroll down and press the button marked “Create my access token”:

After a moment, you’ll see entries for the OAuth consumer key, consumer secret, access token, and access token secret (they’ll look like long strings of random characters). These tokens can be passed to twitter4j or another Twitter library to log into Twitter.