The Price of all “Rest with Spring” course packages will increase by $50 next Friday:


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 – 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(;
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 =;
    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.

The Price of all “Rest with Spring” course packages will increase by $50 next Friday:


Sort by:   newest | oldest | most voted
Marius Donici

Hey…Good job.

How can you manage to have a web application using the twitter stream with multiple users that want to filter a stream differently.Let’s say a guy want the tweets from New York and another guy want the tweets from L.A..Single the twitter api specifies that you can only have one stream connection open how could I handle this do you have any idea :)?

Grzegorz Piwowarek

Well, since the limitation exists per access key, you would probably need to require each user to configure their own credentials that would be used for accessing independent feeds. The other solution would be to configure and manage a pool of N access keys that would allow for N individual streams.

Other than this, I bet that Twitter has a commercial plan for this. I guess this is the right way to go but if you want a free access, above approaches can give you an idea where to start from. At lest this is where I would start from

Marius Donici
Thank you for your response.So basically what you are saying is that if I put like a twitter authentication on my web application I could have a public stream for each user? I am asking this because after some research of the twitter api I have found that there are 3 types of stream the user stream,public stream(this is the one I want to use) and the site stream(which if I’m not wrong is deprecated). The idea is that I am not interested in the user’s feed,what I am looking for are the public tweets ,that 1% of the tweets… Read more »