如何使用twitter4j

时间:2015-11-23 03:21:25

标签: java twitter-oauth twitter4j

我正在编写一个应该可以获取特定Twitter用户的推文的应用。所以我必须首先收集屏幕名称然后才能获取推文。我尝试使用以下代码。

package gethometimeline;
import twitter4j.*;
import java.util.*;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;

import java.util.List;

public class GetUserTimeLine {


    public static void main(String[] args) {

                   ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
  .setOAuthConsumerKey("")
  .setOAuthConsumerSecret("")
  .setOAuthAccessToken("")
  .setOAuthAccessTokenSecret("");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();



        try {
            List<Status> statuses;


             Scanner input = new Scanner(System.in);
             System.out.println("Enter Twitter Screen Name: ");
             String user = input.nextLine();

            if (args.length == 1) {
                user = args[0];
                statuses = twitter.getUserTimeline(user);
            } else {
                user = twitter.verifyCredentials().getScreenName();
                statuses = twitter.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);
        }
    }

通过运行此代码,我获得了用户的推文,其用户的消费者密钥和消费者密钥在配置中输入。但我需要获取特定屏幕名称的推文。

1 个答案:

答案 0 :(得分:2)

示例为用户推文here实施twitter4j。 运行程序时,需要将用户名作为命令行参数传递。我没有看到此代码的任何其他问题