Twitter4j: a Java library to interact with the Twitter API

The Twitter API is one of which I love the most. Its simplicity and richness of functionalities make it a worthwhile experience for a programmer to do.

First and foremost you need to import the library into your Java project, you can do it with Eclipse via Maven, or you can use your preferred IDE, you can also import the library in your Android application through Gradle. Here is how to do it:

On your pom.xml on Eclipse:

<dependencies>
  <dependency>
       <groupId>org.twitter4j</groupId>
       <artifactId>twitter4j-core</artifactId>
       <version>[4.0,)</version>
  </dependency>
</dependencies>

On your build.gradle on Android Studio:

// https://mvnrepository.com/artifact/org.twitter4j/twitter4j-core
compile group: 'org.twitter4j', name: 'twitter4j-core', version: '4.0.6'

The next thing you’re gonna have to do is to create an app on your Twitter account. Of course, they will give some credentials you will have to use to instanciate the main Twitter class. Here it is:

package yourdomain.yourpackage;

import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;

public class TwitterInstance {

  public static ConfigurationBuilder getConfigurationBuilder() {

    ConfigurationBuilder cb = new ConfigurationBuilder();

    return cb.setDebugEnabled(true)
      .setOAuthConsumerKey("your_consumer_key")
      .setOAuthConsumerSecret("your_consumer_secret")
      .setOAuthAccessToken("your_access_token")
      .setOAuthAccessTokenSecret("your_access_token_secret");

  }

  public static Twitter getTwitterInstance() {

    ConfigurationBuilder cb = getConfigurationBuilder();

    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    return twitter;

  }

}

Here you’re creating a class named TwitterInstance, in which substantially you build and return a Twitter instance.

The last thing is to get the instance and any other information it can provide, like statuses for example, in your main class:

Twitter twitter = TwitterInstance.getTwitterInstance();
List<twitter4j.Status> statuses = twitter.getHomeTimeline();

for (Status status : statuses) {
  System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
}

This is not a real world example, but I hope that’s enough to get you started. Consider also that the Twitter API has a limit on the quantity of API calls you can issue for a certain amount of time.

For completeness here is the project’s homepage: Twitter4j, you will find the documentation and all you need to begin.

Did you like this post? Please share it on your preferred social network, thank you!