1. Overview

In this article, we will have a look at using Twitter4J in a Java application to communicate with Twitter.

2. Twitter4J

Twitter4J is an open source Java library, which provides a convenient API for accessing the Twitter API.

Simply put, here’s how we can interact with the Twitter API; we can:

  • Post a tweet
  • Get timeline of a user, with a list of latest tweets
  • Send and receive direct messages
  • Search for tweets and much more

This library ensures that we can easily do these operations, and it also ensures the security and privacy of a user – for which we naturally need to have OAuth credentials configured in our app.

3. Maven Dependencies

We need to start by defining the dependency for Twitter4J in our pom.xml:


To check if any new version of the library has been released – track the releases here.

4. Configuration

Configuring Twitter4J is easy and can be done in various ways – for example in a plain text file or a Java class or even using environment variables.

Let’s look at each of these ways, one at a time.

4.1. Plain Text File

We can use a plain text file – named twitter4j.properties – to hold our configuration details. Let’s look at the properties which need to be provided:

oauth.consumerKey =       // your key
oauth.consumerSecret =    // your secret
oauth.accessToken =       // your token
oauth.accessTokenSecret = // your token secret

All these attributes can be obtained from Twitter Developer console after you make a new app.

4.2. Java Class

We can also use a ConfigurationBuilder class to configure Twitter4J programmatically in Java:

ConfigurationBuilder cb = new ConfigurationBuilder();
  .setOAuthConsumerKey("your consumer key")
  .setOAuthConsumerSecret("your consumer secret")
  .setOAuthAccessToken("your access token")
  .setOAuthAccessTokenSecret("your access token secret");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();

Note that we’ll be using the Twitter instance in next section – when we start to fetch data.

4.3. Environment Variables

Configuring through environment variables is another choice we have. If we do that, note that we’ll need a twitter4j prefix in our variables:

$ export twitter4j.oauth.consumerKey =       // your key
$ export twitter4j.oauth.consumerSecret =    // your secret
$ export twitter4j.oauth.accessToken =       // your access token
$ export twitter4j.oauth.accessTokenSecret = // your access token secret

5. Adding / Retrieving Real-Time Tweet Data

With a fully configured application, we can finally interact with Twitter.

Let’s look at few examples.

5.1. Post a Tweet

We’ll start by updating a tweet on Twitter:

public String createTweet(String tweet) throws TwitterException {
    Twitter twitter = getTwitterinstance();
    Status status = twitter.updateStatus("creating baeldung API");
    return status.getText();

By using status.getText(), we can retrieve the tweet just posted.

5.2. Get the Timeline

We can also fetch a list of tweets from the user’s timeline:

public List<String> getTimeLine() throws TwitterException {
    Twitter twitter = getTwitterinstance();
    return twitter.getHomeTimeline().stream()
      .map(item -> item.getText())

By using twitter.getHomeTimeline(), we get all tweets posted by the current account ID.

5.3. Send a Direct Message

Sending and receiving a direct message to followers is also possible using the Twitter4j:

public static String sendDirectMessage(String recipientName, String msg) 
  throws TwitterException {
    Twitter twitter = getTwitterinstance();
    DirectMessage message = twitter.sendDirectMessage(recipientName, msg);
    return message.getText();

The sendDirectMessage method takes two parameters:

  • RecipientName: the twitter username of a message recipient
  • msg: message content

If recipient will not be found, the sendDirectMessage will throw an exception with exception code 150.

5.4. Search for Tweets

We can also search for tweets containing some text. By doing this, we’ll get a list of tweets with the username of users.

Let’s see how such a search can be performed:

public static List<String> searchtweets() throws TwitterException {
    Twitter twitter = getTwitterinstance();
    Query query = new Query("source:twitter4j baeldung");
    QueryResult result = twitter.search(query);
    return result.getTweets().stream()
      .map(item -> item.getText())

Clearly, we can iterate over each tweet received in a QueryResult and fetch relative data.

5.5. The Streaming API

Twitter Streaming API is useful when updates are required in real-time; it handles thread creation and listens to events.

Let’s create a listener which listens to tweet updates from a user:

public static void streamFeed() {

    StatusListener listener = new StatusListener() {

        public void onException(Exception e) {
        public void onDeletionNotice(StatusDeletionNotice arg) {
        public void onScrubGeo(long userId, long upToStatusId) {
        public void onStallWarning(StallWarning warning) {
        public void onStatus(Status status) {
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();



We can put some println() statement to check the output tweet stream in all of the methods. All tweets have location metadata associated with it.

Please note that all the tweets data fetched by the API are in the UTF-8 format and since Twitter is a multi-language platform, some data format may be unrecognizable based upon its origin.

6. Conclusion

This article was a quick but comprehensive introduction to using Twitter4J with Java.

The implementation of shown examples can be found on GitHub – this is a Maven based project, so it should be easy to import and run as it is. The only change we need to do is to insert our own OAuth credentials.

Course – LS (cat=Java)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:


res – REST with Spring (eBook) (everywhere)