如何使用Twitter4j库在公共推文中进行搜索?
public static void main(String[] args) {
Twitter twitter = new TwitterFactory().getInstance();
try {
Query query = new Query("Cocaine");
QueryResult result;
do {
result = twitter.search(query);
List<Status> tweets = result.getTweets();
for (Status tweet : tweets) {
System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
}
} while ((query = result.nextQuery()) != null);
System.exit(0);
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}
}
这给了我Authentication credentials are missing.
错误
答案 0 :(得分:21)
您需要为Twitter注册您的应用。只有拥有自己的私人帐户才能这样做。获得ConsumerKey
,ConsumerSecret
,AccessToken
和AccessTokenSecret
后,您将在注册申请时向他们展示,最简单的解决方案是将代码更改为以下示例:
public static void main(String[] args) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("yourConsumeKey")
.setOAuthConsumerSecret("yourConsumerSecret")
.setOAuthAccessToken("yourAccessToken")
.setOAuthAccessTokenSecret("yourTokenSecret");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
try {
Query query = new Query("Cocaine");
QueryResult result;
result = twitter.search(query);
List<Status> tweets = result.getTweets();
for (Status tweet : tweets) {
System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
}
System.exit(0);
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}
}
答案 1 :(得分:3)
您需要注册您的应用程序以获取OAuth Authentication Consumerkey,consumersecret以及Accesstoken和Accesstokensecret,并将这些值提供给配置构建器类。
答案 2 :(得分:0)