我正在使用 Twitter4J (2.1.0) 来尝试更新推文。我无法弄清楚我的代码有什么问题。
特别是我的问题是:
(a) 并非所有推文都能成功发布。我经常得到-1的错误代码。根据谷歌群组帖子...
当内部 http 组件无法连接到 API 或无法从 API 读取时,您会得到代码 -1。当由于 DNS 相关问题而无法从 JVM 访问 API 时,您也可能会得到代码 -1。
奇怪的是,我似乎几乎每隔一个帖子就会收到这个。为了解决这个问题,每当我收到 -1 错误代码时,我都会尝试再次更新。虽然我意识到这不是一个很好的解决方案。这在 95% 的时间内修复了问题
(b) 每当新推文与任何旧推文匹配时,我都会收到重复错误(错误代码 403)
即使副本现在已过时,也会出现错误代码 403(例如,发布“Hello there”,发布各种状态更新,然后再次发布“Hello there”会引发带有错误代码 403 的 TwitterException)
我现在的代码...
我的代码位于 AsyncTask 中,而 AsyncTask 又位于 Service(而不是活动)中。我在下面包含了 Asynctask 代码和另一种方法....
class SendTwitAsyncTask extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
String tokenTwit = params[0];
String tokenSecretTwit = params[1];
String strMessageBody = params[2];
AccessToken aToken = new AccessToken(tokenTwit, tokenSecretTwit);
// initialize Twitter4J
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
twitter.setOAuthAccessToken(aToken);
// create a tweet
// strMessageBody varies
String tweet = strMessageBody;
boolean bool = twitter.isOAuthEnabled();
if (twitter.isOAuthEnabled()) {
GeoLocation geolocation = new GeoLocation(-33.91, 151.25);
try {
twitter.updateStatus(tweet, geolocation);
showNotification("Twitter One" , TWIT_SUCCESS);
} catch (TwitterException te) {
if (te.getStatusCode() == -1) {
//try again
try {
twitter.updateStatus(tweet, geolocation);
showNotification("Twitter Two ", TWIT_SUCCESS);
}
catch (TwitterException tetwo) {
describeTwitException(tetwo.getStatusCode());
}
} //end if
//else exception other than -1
else {
describeTwitException(te.getStatusCode());
} //end else
}// end outer catch
} //end if
else {
showNotification("Unable to authenticate" , TWIT_FAIL);
}//
return null;
}
} //end class SendTwitAsyncTask
public void describeTwitException(int twitExceptionCode) {
switch (twitExceptionCode) {
case (-1):
showNotification("Twitter (unable to connect)", TWIT_FAIL);
break;
case(403):
showNotification("Twitter (duplicate tweet)", TWIT_FAIL);
break;
default:
showNotification("Twitter", TWIT_FAIL);
} //end switch
} //end describeTwitException method