Introduction to Twitter4J

Twitter APIs

Twitter offers several APIs to access its services: from account viewing operations (tweets, friends and followers lists, etc.) to editing operations (deleting friends, posting tweets, etc.).

Twitter4J bookshop logo

REST APIs

A set of APIs accessible via REST. These work with OAuth access associated with your account and return results in JSON. The APIs are very complete and will allow you to consult all accounts (public information if it is not your account), and to modify your account.

Please note that Twitter imposes a quota(details) on the number of calls per hour. For example, some functions are limited to 15 calls per hour. When a quota is reached, the API raises an exception and only releases access to the feature after one hour. Please refer to the documentation for method-specific quotas.

Streaming APIs

Some APIs would be difficult to use if the call quotas were respected. These are therefore accessible without limit by maintaining a connection to Twitter. See the documentation for more information.

The Twitter4J bookshop

Introduction

Twitter4J is a library facilitating the use of Twitter APIs (both REST and Streaming).

Written in Java5, it can run on a standard JVM as well as on Android. Twitter APIs version 1.1 is supported (that's enough), handles OAuth, and doesn't depend on any third-party library.

It is available on the Maven Central repository:

<dependency>
  <groupId>org.twitter4j</groupId>
  <artifactId>twitter4j-core</artifactId>
  <version>4.0.4</version>
</dependency>

Case study

We are going to use Twitter4J to do the following on our account: delete our friends (those we follow) who are not our followers (those who follow us). In other words, stop following people who don't follow us.

This can be useful because the maximum number of friends is a function of the number of followers. A company wishing to optimise its friends should therefore regularly clean up its relationships.

1) The algorithm

We will :

  • log in to our account via OAuth
  • list all our followers
  • list all our friends and stop following those who are not also our followers

2) OAuth

Before you can use the Twitter APIs, you need to get OAuth access. The procedure is explained in the developer documentation. I'll spare you the trouble of reading it and summarise the steps to follow:

  • go to https://apps.twitter.com and log in with your Twitter account
  • create a new application (the button at the top right "Create New App") and fill in the form that appears
  • a summary of the application is displayed, with a link "(manage keys and access tokens)" in front of "Consumer Key": click on it
  • note your "Consumer Key" and "Consumer Secret
  • at the bottom of the page, click on the "Create my access token" button
  • note your "Access Token" and "Access Token Secret

The Consumez Key, Consumer Secret, Access Token and Access Token Secret are the four parameters that will allow you to authenticate via OAuth. Depending on the rights you have given to the application (Read Write by default), this access will give you both read and write access to your Twitter account. It will also give you (partial) read access to other users' accounts. So keep this information secret.

3) The code

  • log in using OAuth :
import java.util.*;
import twitter4j.*;
...
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("Your Consumer Key Here")
  .setOAuthConsumerSecret("Your Consumer Secret Here")
  .setOAuthAccessToken("Your Access Token Here")
  .setOAuthAccessTokenSecret("Your Access Token Secret Here");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter tw = tf.getInstance();
  • list your followers and friends and search for friends to delete.
    You will notice that the APIs listing friends and followers are paginable. Think to consult the documentation to know the maximum size of a page and thus preserve your quota of calls):
String twAccountName = "Notre ScreenName Twitter";

 Récupérer nos followers.
List<String> followers = new ArrayList<>(256);
PagableResponseList<User> followersList;
int countPages = 0;
long cursor = -1;
do {
  followersList = tw.friendsFollowers().getFollowersList(tw, twAccountName, cursor, 200);
  for (User user : followersList) {
    followers.add(user.getScreenName());
  }
} while ((cursor = followersList.getNextCursor()) != 0 && ++countPages < 15);

 Récupérer nos friends...
PagableResponseList<User> friendsList;
countPages = 0;
cursor = -1;
do {
  friendsList = tw.friendsFollowers().getFriendsList(tw, twAccountName, cursor, 200);
  for (User user : friendsList) {
     ...et arrêter de suivre les friends qui ne nous suivent pas
    String friendScreenName = user.getScreenName();
    if (!followers.contains(friendScreenName)) {
      tw.destroyFriendship(friendScreenName);
    }
  }
} while ((cursor = friendsList.getNextCursor()) != 0 && ++countPages < 15);

Our account has now stopped following friends who are not followers. The removal of these relationships is effective immediately and cannot be undone.

Conclusion

Twitter4J is an accessible library and supports most of the Twitter APIs. It works on both PC and smartphone. What more could you ask for?

For those who would like to go further into the APIs of social networks, you should know that there is an equivalent of this library for Facebook: Facebook4J. The interfaces are surprisingly similar, so you won't be lost.

 

Are you interested in this topic?

CONTACT US