我目前正在尝试根据Twitter状态ID:s的长列表(> 50k)获取一组状态。目前我正在使用Java和twitter4j。如果可能的话,我真的想避免对每个id进行单独调用,但任何比我当前代码更快的方法(见下文)都会非常感激。
public class TweetById {
private static String consumerKey = ...;
private static String consumerSecret = ...;
private static String accessToken = ...;
private static String accessTokenSecret = ...;
public static void main(String[] args) {
// connect to Twitter
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true);
cb.setOAuthConsumerKey(consumerKey);
cb.setOAuthConsumerSecret(consumerSecret);
cb.setOAuthAccessToken(accessToken);
cb.setOAuthAccessTokenSecret(accessTokenSecret);
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
String[] ids = new String[]{"327664925705109505", "327665399644696576","327666368516341761"};
for(String id : ids){
try {
Status status = twitter.showStatus(Long.parseLong(id));
System.out.println("Time: " + status.getCreatedAt() + ": " + status.getText());
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (TwitterException e) {
e.printStackTrace();
}
}
}
}
编辑: 我现在尝试在twitter4j中使用异步方法,但我似乎无法使其工作。我有什么遗失的吗?
public class TweetById {
private static String consumerKey = ...;
private static String consumerSecret = ...;
private static String accessToken = ...;
private static String accessTokenSecret = ...;
public static void main(String[] args) {
// connect to Twitter
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true);
cb.setOAuthConsumerKey(consumerKey);
cb.setOAuthConsumerSecret(consumerSecret);
cb.setOAuthAccessToken(accessToken);
cb.setOAuthAccessTokenSecret(accessTokenSecret);
// The factory instance is re-useable and thread safe.
AsyncTwitterFactory factory = new AsyncTwitterFactory(cb.build());
AsyncTwitter asyncTwitter = factory.getInstance();
asyncTwitter.addListener(new TwitterAdapter() {
@Override
public void gotShowStatus(Status status) {
System.out.println("Time: " + status.getCreatedAt() + ": " + status.getText());
}
});
String[] ids = new String[] { "327664925705109505", "327665399644696576", "327666368516341761" };
for (String id : ids) {
asyncTwitter.showStatus(Long.parseLong(id));
}
}
}