我正在尝试使用 twitter4j api 从 twitter api 检索数据。一段时间后检索数据我收到以下错误:
Exception in thread "main" 403:The request is understood, but it has been refused. An accompanying error message will explain why. This code is used when requests are being denied due to update limits (https://support.twitter.com/articles/15364-about-twitter-limits-update-api-dm-and-following).
message - User has been suspended.
code - 63
我得出的结论是,上述错误源于 twitter api 支持的调用的限制。如何创建间隔以便等待可以从 Twitter 获取数据?
例如我的代码如下:
Long l = Long.parseLong(list.get(index));
TwitterResponse response = twitter.getFollowersIDs(l);
RateLimitStatus status = response.getRateLimitStatus();
if (status.getRemaining() < 2) {
try {
System.out.println("status.getSecondsUntilReset()");
Thread.sleep(status.getSecondsUntilReset());
} catch (InterruptedException e) {
System.out.println(e);
}
}
User user = twitter.showUser((l));
//statuses = twitter.getUserTimeline(l);
JSONObject features = new JSONObject();
features.put("_id", l);
score = kloutScore(l);
我的新代码包含一个 if 语句,该语句检查 status.getRemaining() 是否接近于零,然后等待 15 分钟,这实际上是限制持续时间。但是我遇到了 TwitterResponse response = twitter.getFollowerIDs(l); 的问题我收到消息:
Exception in thread "main" 429:Returned in API v1.1 when a request cannot be served due to the application's rate limit having been exhausted for the resource. See Rate Limiting in API v1.1.(https://dev.twitter.com/docs/rate-limiting/1.1)
message - Rate limit exceeded
最佳答案
对于每个响应,您可以调用 getRateLimitStatus()
来获取 RateLimitStatus
。 RateLimitStats.getRemaining()
将告诉您该系列调用可用的 API 请求的剩余数量,如果达到零,您可以调用 RateLimitStatus.getSecondsUntilReset()
,并且至少等待那么长时间,然后再进行其他调用。
有关 Twitter 速率限制的信息可在此处找到:https://dev.twitter.com/docs/rate-limiting/1.1
这是一个基本示例:
do {
TwitterResponse response = twitter.getFollowersIDs(userId, cursor);
RateLimitStatus status = response.getRateLimitStatus();
if(status.getRemaining() == 0) {
try {
Thread.sleep(status.getSecondsUntilReset() * 1000);
}
catch(InterruptedException e) {
// ...
}
}
} while(cursor > 0);
在您现在提供的代码中,您正在对 Twitter 进行 2 次调用:showUser
和 getUserTimeLine
。您需要在这两个调用之后检查速率限制状态(User
和 ResponseList
都扩展 TwitterResponse
并具有速率限制信息)。这些调用属于 2 个不同的资源系列(users
和 statuses
),这两种方法都允许在每个速率限制窗口(15 分钟)内调用 180 次。
关于java - Twitter API 更新限制错误 403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23536721/