package beproject1;
import twitter4j.FilterQuery;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.User;
import twitter4j.conf.ConfigurationBuilder;
public class Twitter {
public static void main(String[] args)
{
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("ab")
.setOAuthConsumerSecret("cd")
.setOAuthAccessToken("ef")
.setOAuthAccessTokenSecret("gh")
;
TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
StatusListener listener = new StatusListener() {
@Override
public void onException(Exception arg0) {
// TODO Auto-generated method stub
}
@Override
public void onDeletionNotice(StatusDeletionNotice arg0) {
// TODO Auto-generated method stub
}
public void onScrubGeo(long arg0, long arg1) {
// TODO Auto-generated method stub
}
@Override
public void onStatus(Status status) {
User user = status.getUser();
// gets Username
String username = status.getUser().getScreenName();
System.out.println(username);
String profileLocation = user.getLocation();
System.out.println(profileLocation);
long tweetId = status.getId();
System.out.println(tweetId);
String content = status.getText();
System.out.println(content +"\n");
}
@Override
public void onTrackLimitationNotice(int arg0) {
// TODO Auto-generated method stub
}
};
FilterQuery fq = new FilterQuery();
String keywords[] = {"ireland"};
fq.track(keywords);
twitterStream.addListener(listener); // this line errors out
twitterStream.filter(fq);
}
}
声明twitterStream.addListener(listener)
的行显示错误。
它表示addListener
没有为类型twitterStream
定义。
谁能告诉我为什么?
我尝试过包含其他twitter4j
罐子,但问题仍然存在。
答案 0 :(得分:1)
这是使用Twitter4J在流中捕获推文的正确方法:
// Prepare configuration.
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey(Config.TwitterConsumerKey);
configurationBuilder.setOAuthConsumerSecret(Config.TwitterConsumerSecret);
configurationBuilder.setOAuthAccessToken(Config.OAuthAccessToken);
configurationBuilder.setOAuthAccessTokenSecret(Config.OAuthAccessTokenSecret);
// Create the Twitter stream object.
twitterStream = new TwitterStreamFactory(configurationBuilder.build()).getInstance();
twitterStream.addListener(new StreamListener());
// Crawl.
FilterQuery filterQuery = new FilterQuery();
filterQuery.follow([your_set_of_user_IDs]);
filterQuery.track([your_set_of_keywords]);
twitterStream.filter(filterQuery);
请注意StreamListener
是实现StatusListener
接口的具体类,您可以在其中定义捕获推文时要执行的操作。