Twitter4J验证凭据并捕获错误

时间:2013-02-13 17:54:59

标签: java google-app-engine twitter4j

我在google appengine上有以下代码,以测试twitter凭据是否有效使用twitter4j

public void doGet(HttpServletRequest req, HttpServletResponse resp) {
    String Test = "Testing Twitter4J";
    try {

        ConfigurationBuilder confbuilder  = new ConfigurationBuilder();
        confbuilder.setOAuthAccessToken("A") 
        .setOAuthAccessTokenSecret("B") 
        .setOAuthConsumerKey("C") 
        .setOAuthConsumerSecret("D"); 
        Twitter twitter = new TwitterFactory(confbuilder.build()).getInstance(); 

        //Status status = twitter.updateStatus("Working lunch today");
        User user = twitter.verifyCredentials();
        Test = "Successfully updated the status to [" + user.getScreenName() + "].";

    } catch (TwitterException e) {
        Test =  "no";
    }
    try {
        resp.getOutputStream().write(Test.getBytes());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return;
}

如果凭据有效,则按预期工作。如果我撤销访问权限以使凭据无效,则会收到应用引擎错误:

Uncaught exception from servlet
twitter4j.TwitterRuntimeException: 401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
message - Invalid or expired token
code - 89

Relevant discussions can be found on the Internet at:
    http://www.google.co.jp/search?q=93f2523c or
    http://www.google.co.jp/search?q=8b74a4e3
TwitterException{exceptionCode=[93f2523c-8b74a4e3], statusCode=401, message=Invalid or expired token, code=89, retryAfter=-1, rateLimitStatus=null, version=3.0.3}
来自“User user = twitter.verifyCredentials();”的

线。我期待从javadoc抛出TwitterException: http://twitter4j.org/javadoc/twitter4j/api/UsersResources.html#verifyCredentials() 但似乎我得到了一个TwitterRuntimeException。为什么?我在javadocs中找不到任何关于TwitterRuntimeException的注释。

1 个答案:

答案 0 :(得分:1)

对我来说,解决方案如下:

  • 转到twitter app
  • 选择设置标签
  • 在应用程序类型 - 访问 - 选择最后一个选项读取,写入 和访问直接消息

如果这不能解决问题,请尝试添加回调URL。你可以把任何网址放在这里,没关系。