Code Examples

Sample codes are located under twitter4j-examples/src/twitter4j/examples/.

To run the example codes, you need to have OAuth credentials configured in twitter4j.properties. See Twitter4J – Configuration for the detail.

Post a Tweet

You can tweet using TweetResources.updateStatus() method.
See also twitter4j.examples.tweets.UpdateStatus.java for the detail.

Twitter twitter = Twitter.getInstance();
Status status = twitter.v1().tweets().updateStatus(latestStatus);
System.out.println("Successfully updated the status to [" + status.getText() + "].");

Get Timeline

TimelineResources.getHomeTimeline() returns a List of the latest tweets from user’s home timeline.
See also twitter4j.examples.timeline.GetHomeTimeline.java for the detail.

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.v1.Status;

import java.util.List;

class Main {
    public static void main(String[] args) throws TwitterException {
        Twitter twitter = Twitter.getInstance();
        List<Status> statuses = twitter.v1().timelines().getHomeTimeline();
        System.out.println("Showing home timeline.");
        for (Status status : statuses) {
            System.out.println(status.getUser().getName() + ":" +
                    status.getText());
        }
    }
}

Send / Receive Direct Messages

You can send and receive direct messages via Twitter.sendDirectMessage() / Twitter.getDirectMessages().
See also twitter4j.examples.directmessage.SendDirectMessage.java for the detail.

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.v1.DirectMessage;

class Main {
    public static void main(String[] args) throws TwitterException {
        long recipientId = Long.parseLong(args[0]);
        String message = args[1];
        Twitter twitter = Twitter.getInstance();
        DirectMessage directMessage = twitter.v1().directMessages().sendDirectMessage(recipientId, message);
        System.out.printf("Sent: %s to @%d%n", directMessage.getText(), directMessage.getRecipientId());
    }
}

You can search for Tweets using Query class and Twitter.search(twitter4j.Query) method.
See twitter4j.examples.search.SearchTweets.java for the detail.

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.v1.Query;
import twitter4j.v1.QueryResult;
import twitter4j.v1.Status;

class Main {
    public static void main(String[] args) throws TwitterException {
        Twitter twitter = Twitter.getInstance();
        Query query = Query.of("source:twitter4j yusukey");
        QueryResult result = twitter.v1().search().search(query);
        for (Status status : result.getTweets()) {
            System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText());
        }
    }
}

Page control

Some API supports pagination. Those APIs accept following parameters:

page: page
count: number of elements per page
since_id: returns elements which id are biggar than the specified id
max_id: returns elements which id are smaller than the specified id

You can use Paging class to specify those parameters.

Note that some of above parameters are not accepted by those APIs. Please refer the Support API Matrix to see which parameters are accepted by which methods.

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.v1.Paging;
import twitter4j.v1.TimelinesResources;

class Main {
    public static void main(String[] args) throws TwitterException {
        TimelinesResources twitter = Twitter.getInstance().v1().timelines();
        // requesting page 2, number of elements per page is 40
        twitter.getMentionsTimeline(Paging.ofPage(2).count(40))
                .forEach(tweet ->
                        System.out.printf("%s:%s%n", tweet.getUser().getScreenName(), tweet.getText()));

        // requesting page 3, since_id is (long)1000
        twitter.getMentionsTimeline(Paging.ofPage(3).sinceId(1000L))
                .forEach(tweet ->
                        System.out.printf("%s:%s%n", tweet.getUser().getScreenName(), tweet.getText()));
    }
}

OAuth support

With OAuth authorization scheme, an application can access the user account without userid/password combination given. You need to register your application at https://twitter.com/oauth_clients/new to acquire consumer key, and consumer secret in advance. key / secret pair can be set via Twitter#setOAuthConsumer(), or following system properties:

-Dtwitter4j.oauth.consumerKey=[consumer key]
-Dtwitter4j.oauth.consumerSecret=[consumer secret]

Initially, you don’t have a permission to access the user’s account and need to acquire access token by redirecting the user to an authorization URL as follows:

import twitter4j.*;
import twitter4j.v1.Status;

import java.util.Scanner;

class Main {
    public static void main(String[] args) throws TwitterException {
        String consumerKey = "[consumer key]";
        String consumerSecret = "[consumer secret]";
        OAuthAuthorization oAuth = OAuthAuthorization.newBuilder()
                .oAuthConsumer(consumerKey, consumerSecret).build();
        RequestToken requestToken = oAuth.getOAuthRequestToken();
        AccessToken accessToken = null;
        try (Scanner scanner = new Scanner(System.in)) {
            while (null == accessToken) {
                System.out.println("Open the following URL and grant access to your account:");
                System.out.println(requestToken.getAuthorizationURL());
                System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
                String pin = scanner.nextLine();
                try {
                    if (pin.length() > 0) {
                        accessToken = oAuth.getOAuthAccessToken(requestToken, pin);
                    } else {
                        accessToken = oAuth.getOAuthAccessToken();
                    }
                } catch (TwitterException te) {
                    if (401 == te.getStatusCode()) {
                        System.out.println("Unable to get the access token.");
                    } else {
                        te.printStackTrace();
                    }
                }
            }
        }
        Twitter twitter = Twitter.newBuilder().oAuthConsumer(consumerKey, consumerSecret)
                .oAuthAccessToken(accessToken).build();
        //persist to the accessToken for future reference.
        storeAccessToken(twitter.v1().users().verifyCredentials().getId(), accessToken);
        Status status = twitter.v1().tweets().updateStatus(args[0]);
        System.out.println("Successfully updated the status to [" + status.getText() + "].");
        System.exit(0);
    }

    private static void storeAccessToken(long userId, AccessToken accessToken) {
        //store accessToken.getToken()
        //store accessToken.getTokenSecret()
    }
}

After you acquired the AccessToken for the user, the RequestToken is not required anymore. You can persist the AccessToken to any kind of persistent store such as RDBMS, or File system by serializing the object, or by geting the token and the secret from AccessToken#getToken() and AccessToken#getTokenSecret().

Sign in with Twitter

import twitter4j.*;
import twitter4j.v1.Status;

class Main {
    public static void main(String[] args) throws Exception {
        long userId = Long.parseLong(args[0]);
        String accessToken = loadAccessToken(userId);
        String accessTokenSecret = loadAccessTokenSecret(userId);
        Twitter twitter = Twitter.newBuilder()
                .oAuthConsumer("[consumer key]", "[consumer secret]")
                .oAuthAccessToken(accessToken, accessTokenSecret).build();
        Status status = twitter.v1().tweets().updateStatus(args[1]);
        System.out.println("Successfully updated the status to [%s].".formatted(status.getText()));
        System.exit(0);
    }

    private static String loadAccessToken(long userId) {
        return "[token]"; // load from a persistent store
    }

    private static String loadAccessTokenSecret(long userId) {
        return "[token secret]"; // load from a persistent store
    }
}

See also: Twitter API Wiki / OAuth FAQ

Sign in with Twitter

It is possible to authenticate users using Twitter accounts with your web application. To achieve that, simply pass a callback URL upon RequestToken retrieval, and then get the AccessToken with the oauth_verifier parameter which will be added to the callback URL upon callback.
An example implementation is available at https://github.com/yusuke/sign-in-with-twitter.

Streaming API

TwitterStream class has several methods prepared for the streaming API. All you need is to have a class implementing StatusListener. Twitter4J will do creating a thread, consuming the stream.
See also twitter4j.examples.stream.PrintSampleStream.java for the detail.

import twitter4j.*;
import twitter4j.v1.*;

import java.io.IOException;

class Main {
    public static void main(String[] args) throws TwitterException, IOException {
        StatusListener listener = new StatusListener(){
            @Override
            public void onStatus(Status status) {
                System.out.println("%s : %s".formatted(status.getUser().getName(), status.getText()));
            }
            @Override
            public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {}
            @Override
            public void onTrackLimitationNotice(int numberOfLimitedStatuses) {}

            @Override
            public void onScrubGeo(long userId, long upToStatusId) {}

            @Override
            public void onStallWarning(StallWarning warning) {}

            @Override
            public void onException(Exception ex) {
                ex.printStackTrace();
            }
        };
        TwitterStream twitterStream = Twitter.newBuilder()
                .listener(listener).build().v1().stream();
        // sample() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
        twitterStream.sample();
    }
}

Recent Posts

  1. Twitter4J 4.1.2 released Leave a reply
  2. Twitter4J 4.1.1 released Leave a reply
  3. Twitter4J 4.1.0 released Leave a reply
  4. Twitter4J 4.0.7 リリース Leave a reply
  5. General availability of Twitter4J 4.0.7 Leave a reply
  6. #Twitter4J 4.0.7-SNAPSHOT リリース – DMを利用するアプリは要移行 Leave a reply
  7. releasing #Twitter4J 4.0.7-SNAPSHOT – Apps using DM need to migrate Leave a reply
  8. #Twitter4J 4.0.4 リリース – 長文DMサポート、Lambda表記サポートなど Leave a reply
  9. #Twitter4J 4.0.4 released – supports longer DM texts, lambda expression and more Leave a reply