要明确的是,对于所有匆忙说这些类型的帖子都没有阅读的人都是重复的:这不是一种问题,我问的是什么是null,我该如何管理这些例外,我在这里问为什么twitter的API返回到我的方法一个看似随机的空对象。
我正在创建一个使用Twitter4J库与Twitter API交互的Java应用程序。我想下载大量的推文,然后对离线数据进行统计。推文保存在NoSQL数据库(elasticsearch)中。
我的代码在开始仅在控制台上打印推文进行测试时表现还不错。当我的程序达到max tweets的限制时,它会一直睡到twitter限制的重置(打印超过1.000.000并且零错误),在我开始将推文保存到我的数据库,在一些循环之后,我在这个确切的语句java.lang.NullPointerException
中得到if (searchTweetsRateLimit.getRemaining() == 0)
。有什么建议吗?
public static void main(String[] args) throws TwitterException {
int totalTweets = 0;
long maxID = -1;
twitter4j.Twitter twitter = getTwitter();
RestClient restclient = RestClient.builder(
new HttpHost("localhost",9200,"http"),
new HttpHost("localhost",9201,"http")).build();
Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search");
// This finds the rate limit specifically for doing the search API call we use in this program
RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets");
System.out.printf("You have %d calls remaining out of %d, Limit resets in %d seconds\n",
searchTweetsRateLimit.getRemaining(),
searchTweetsRateLimit.getLimit(),
searchTweetsRateLimit.getSecondsUntilReset());
int i = 10;
// This is the loop that retrieve multiple blocks of tweets from Twitter
for (int queryNumber=0;queryNumber < MAX_QUERIES; queryNumber++)
{
System.out.printf("\n\n!!! Starting loop %d\n\n", queryNumber);
// Do we need to delay because we've already hit our rate limits?
if (searchTweetsRateLimit.getRemaining() == 0)
{
// Yes we do, unfortunately ...
System.out.printf("!!! Sleeping for %d seconds due to rate limits\n", searchTweetsRateLimit.getSecondsUntilReset());
// If you sleep exactly the number of seconds, you can make your query a bit too early
// and still get an error for exceeding rate limitations
Thread.sleep((searchTweetsRateLimit.getSecondsUntilReset()+2) * 1000l);
}
Query q = new Query(SEARCH_TERM); // Search for tweets that contains this term
q.setCount(TWEETS_PER_QUERY); // How many tweets, max, to retrieve
q.resultType(null); // Get all tweets
q.setLang("en"); // English language tweets, please