English | Japanese | Korean

 



Code Examples

Sample codes are located at src/twitter4j/examples/ and you can run each classs using bin/className.cmd|sh.
To run the example codes, you need to have OAuth credentials configured in twitter4j.properties. See Twitter4J - Configuration for the detail.

  1. post a Tweet

  2. You can update "What are you doing?" via Twitter.updateStatus() method.
    See also twitter4j.examples.tweets.UpdateStatus.java for the detail.

        // The factory instance is re-useable and thread safe.
        Twitter twitter = TwitterFactory.getSingleton();
        Status status = twitter.updateStatus(latestStatus);
        System.out.println("Successfully updated the status to [" + status.getText() + "].");
    

  3. Getting Timeline

  4. Twitter.get****Timeline() returns a List of latest tweets from user's home timeline.
    See also twitter4j.examples.timeline.GetHomeTimeline.java for the detail.

        // The factory instance is re-useable and thread safe.
        Twitter twitter = TwitterFactory.getSingleton();
        List<Status> statuses = twitter.getHomeTimeline();
        System.out.println("Showing home timeline.");
        for (Status status : statuses) {
            System.out.println(status.getUser().getName() + ":" +
                               status.getText());
        }
    
    Doesn't work on Java1.4, or Processing? Check the FAQ!

  5. Sending / Receiving Direct Messages

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

        // The factory instance is re-useable and thread safe.
        Twitter sender = TwitterFactory.getSingleton();
        DirectMessage message = sender.sendDirectMessage(recipientId, message);
        System.out.println("Sent: " message.getText() + " to @" + message.getRecipientScreenName());
    
    Doesn't work on Java1.4, or Processing? Check the FAQ!

  7. Search for Tweets

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

        // The factory instance is re-useable and thread safe.
        Twitter twitter = TwitterFactory.getSingleton();
        Query query = new Query("source:twitter4j yusukey");
        QueryResult result = twitter.search(query);
        for (Status status : result.getTweets()) {
            System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText());
        }
    
    Doesn't work on Java1.4, or Processing? Check the FAQ!

  9. Asynchronous API

  10. It is possible to call the time consuming Twitter APIs asynchronously using twitter4j.AsyncTwitter class along with TwitterListener.
    Actual method calls will be done in a separate thread and you can get the responses through TwitterListener interface.
    See also twitter4j.examples.async.AsyncUpdate.java for the detail.

        TwitterListener listener = new TwitterAdapter() {
            @Override public void updatedStatus(Status status) {
              System.out.println("Successfully updated the status to [" +
                       status.getText() + "].");
            }
    
            @Override public void onException(TwitterException e, int method) {
              if (method == TwitterMethods.UPDATE_STATUS) {
                e.printStackTrace();
              } else {
                throw new AssertionError("Should not happen");
              }
            }
        }
        // The factory instance is re-useable and thread safe.
        AsyncTwitterFactory factory = new AsyncTwitterFactory();
        AsyncTwitter asyncTwitter = factory.getInstance();
        asyncTwitter.addListener(listenrer);
        asyncTwitter.updateStatus(args[0]);
    

  11. Pagination control

  12. 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.
        // The factory instance is re-useable and thread safe.
        Twitter twitter = TwitterFactory.getSingleton();
        // requesting page 2, number of elements per page is 40
        Paging paging = new Paging(2, 40);
        List statuses = twitter.getFriendsTimeline(paging);
        for (Status status : statuses) {
            System.out.println(status.getUser().getScreenName() + ":" + status.getText());
        }
    
        // requesting page 3, since_id is (long)1000
        statuses = twitter.getFriendsTimeline(new Paging(3).sinceId(1000l));
        for (Status status : statuses) {
            System.out.println(status.getUser().getScreenName() + ":" + status.getText());
        }
    

  13. OAuth support

  14. With OAuth authorization scheme, an application can access the user account without userid/password combination given. You need to register your application at http://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:
      public static void main(String args[]) throws Exception{
        // The factory instance is re-useable and thread safe.
        Twitter twitter = TwitterFactory.getSingleton();
        twitter.setOAuthConsumer("[consumer key]", "[consumer secret]");
        RequestToken requestToken = twitter.getOAuthRequestToken();
        AccessToken accessToken = null;
        BufferedReader br = new BufferedReader(new InputStreamReader(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 = br.readLine();
          try{
             if(pin.length() > 0){
               accessToken = twitter.getOAuthAccessToken(requestToken, pin);
             }else{
               accessToken = twitter.getOAuthAccessToken();
             }
          } catch (TwitterException te) {
            if(401 == te.getStatusCode()){
              System.out.println("Unable to get the access token.");
            }else{
              te.printStackTrace();
            }
          }
        }
        //persist to the accessToken for future reference.
        storeAccessToken(twitter.verifyCredentials().getId() , accessToken);
        Status status = twitter.updateStatus(args[0]);
        System.out.println("Successfully updated the status to [" + status.getText() + "].");
        System.exit(0);
      }
      private static void storeAccessToken(int useId, 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().
      public static void main(String args[]) throws Exception{
        // The factory instance is re-useable and thread safe.
        TwitterFactory factory = new TwitterFactory();
        AccessToken accessToken = loadAccessToken(Integer.parseInt(args[0]));
        Twitter twitter = factory.getInstance);
        twitter.setOAuthConsumerKey("[consumer key]", "[consumer secret]");
        twitter.setOAuthAccessToken(accessToken);
        Status status = twitter.updateStatus(args[1]);
        System.out.println("Successfully updated the status to [" + status.getText() + "].");
        System.exit(0);
      }
      private static AccessToken loadAccessToken(int useId){
        String token = // load from a persistent store
        String tokenSecret = // load from a persistent store
        return new AccessToken(token, tokenSecret);
      }
    
    See also: Twitter API Wiki / OAuth FAQ

  15. Sign in with Twitter

  16. 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 http://github.com/yusuke/sign-in-with-twitter.

  17. Streaming API

  18. 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.

    public static void main(String[] args) throws TwitterException, IOException{
        StatusListener listener = new StatusListener(){
            public void onStatus(Status status) {
                System.out.println(status.getUser().getName() + " : " + status.getText());
            }
            public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {}
            public void onTrackLimitationNotice(int numberOfLimitedStatuses) {}
            public void onException(Exception ex) {
                ex.printStackTrace();
            }
        };
        TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
        twitterStream.addListener(listener);
        // sample() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
        twitterStream.sample();
    }
    
    Doesn't work on Java1.4, or Processing? Check the FAQ!