Twitter4j:Oauth无法正常工作

时间:2018-07-02 19:18:57

标签: java twitter oauth twitter4j

正在努力获取可用的twitter4j实例,但Oauth遇到问题。我多次复制粘贴,创建了不同的应用程序和键/令牌,但仍然无法正常工作。我在这里真的会做错什么?

我的主:

public class Main {

public static void main(String[] args) {
// write your code here

    Tweeter tweet = new Tweeter();
    try{
        tweet.searchTweets();

    } catch (TwitterException e) {
            e.printStackTrace();
        }
}
}

我的推特课程:

public class Tweeter {

public static Twitter GetTwitterInstance(){

    String consumerKey = "**************";
    String consumerSecret = "*************";
    String accessToken = "***************";   // yourt token
    String accessTokenSecret = "************"; // your token secre

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true)
            .setOAuthConsumerKey(consumerKey)
            .setOAuthConsumerSecret(consumerSecret)
            .setOAuthAccessToken(accessToken)
            .setOAuthAccessTokenSecret(accessTokenSecret);

    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getSingleton();

    return twitter;
}

public static void searchTweets() throws TwitterException{

    Twitter twitter = GetTwitterInstance();
    Query query = new Query("something");
    QueryResult result = twitter.search(query);
    List<Status> statuses = result.getTweets();

    for(Status tweet: statuses){
        System.out.println("User: "+tweet.getUser().getScreenName() + " Tweet: "+tweet.getText());
    }
}

}

错误堆栈跟踪:

400:The request was invalid. An accompanying error message will explain why. 
This is the status code will be returned during version 1.0 rate 
limiting(https://dev.twitter.com/pages/rate-limiting). In API v1.1, a request 
without authentication is considered invalid and you will get this response.
message - Bad Authentication data.
code - 215

Relevant discussions can be found on the Internet at:
    http://www.google.co.jp/search?q=506c3b98 or
    http://www.google.co.jp/search?q=11ed9ae8
TwitterException{exceptionCode=[506c3b98-11ed9ae8], statusCode=400, 
message=Bad Authentication data., code=215, retryAfter=-1, 
rateLimitStatus=null, version=4.0.6}
    at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:164)
    at twitter4j.HttpClientBase.request(HttpClientBase.java:57)
    at twitter4j.HttpClientBase.get(HttpClientBase.java:75)
    at twitter4j.TwitterImpl.get(TwitterImpl.java:1786)
    at twitter4j.TwitterImpl.search(TwitterImpl.java:268)
    at Tweeter.searchTweets(Tweeter.java:58)
    at Main.main(Main.java:14)

打印twitter工厂的键/令牌将按预期提供正常的键/令牌,而不会出现奇怪的字符或空格或其他内容。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

您的代码似乎是从已知的工作代码中剪切并粘贴的。再次检查是否没有多余的字符,例如字符串末尾的空格。

答案 1 :(得分:0)

问题是tf.getSingleton()显然没有返回twitter实例。

它应该只是Twitter twitter = tf.getInstance();,然后它可以工作。