Search code examples
javatwitter4j

how to get user timeline using twitter4j


Below is my code. my question is how to get the user timeline of another account? (say a public account like att). I have my consumer key, secret, access token, access secret, which are registered under my twitter account. Please help me. Thank you very much.

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;

import java.util.List;

/**
 * @author Yusuke Yamamoto - yusuke at mac.com
 * @since Twitter4J 2.1.7
 */
public class GetUserTimeline {
    /**
     * Usage: java twitter4j.examples.timeline.GetUserTimeline
     *
     * @param args String[]
     */
    public static void main(String[] args) {
        // gets Twitter instance with default credentials
        Twitter twitter = new TwitterFactory().getInstance();
        try {
            ConfigurationBuilder cb = new ConfigurationBuilder();
            cb.setDebugEnabled(true)
              .setOAuthConsumerKey("***")
              .setOAuthConsumerSecret("***")
              .setOAuthAccessToken("***")
              .setOAuthAccessTokenSecret("***");
            TwitterFactory tf = new TwitterFactory(cb.build());
            Twitter twitter1 = tf.getInstance();
            List<Status> statuses;
            String user;
            if (args.length == 1) {
                user = args[0];
                statuses = twitter1.getUserTimeline("ATT");
            } else {
                user = twitter1.verifyCredentials().getScreenName();
                statuses = twitter1.getUserTimeline();
            }
            System.out.println("Showing @" + user + "'s user timeline.");
            for (Status status : statuses) {
                System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
            }
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to get timeline: " + te.getMessage());
            System.exit(-1);
        }
    }
}

Solution

  • I suspect that if you reverted your change of:

    statuses = twitter1.getUserTimeline("ATT");
    

    to:

    statuses = twitter1.getUserTimeline(user);
    

    and invoked GetUserTimeline with ATT as a command line argument it should work.

    It looks like the twitter4j examples come with utility scripts to execute them, so it seems you should be able to just run:

    $ getUserTimeline.sh ATT