繁体   English   中英

使用Twitter4J和OAuth访问Twitter Stream API

[英]Accessing the Twitter Stream API with Twitter4J and OAuth

我想使用Twitter4J访问Public stream API示例。 我已经在Twitter上创建了一个应用程序,并生成了相关的密钥和令牌(使用Twitter门户)。

但是它一直使认证失败。

这是根据文档的代码。 现有的许多论坛帖子已过时。

ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true);
cb.setOAuthConsumerKey("XXXXX");
cb.setOAuthConsumerSecret("XXXXXXXX");
cb.setOAuthAccessToken("xxxxxxxx-xxxxxxxxxxxxxxxxxxxxxx");
cb.setOAuthAccessTokenSecret("XXXXXXXXXXXXXXXXXXXXXXX");   

OAuthAuthorization auth = new OAuthAuthorization(cb.build());
TwitterStreamFactory factory = new TwitterStreamFactory();
this.twitterStream = factory.getInstance(auth);
this.twitterStream.addListener(listener);
this.twitterStream.sample();

我得到的错误是:

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.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Error 401 Unauthorized</title>
</head>
<body>
<h2>HTTP ERROR: 401</h2>
<p>Problem accessing '/1.1/statuses/sample.json?stall_warnings=true'. Reason:
<pre>    Unauthorized</pre>
</body>
</html>

401错误的原因是身份验证失败。 可能由于两个原因而发生

  • 配置中的凭证不正确 [ 此处介绍了配置凭证的不同方法]

  • 不正确的系统时钟 [即使您认为时间正确也同步系统时钟]

第二个原因可能是当您能够使用API​​发布推文,查看时间轴等而无法使用Twitter流时的原因。[ 仅在使用流API时会获得401 ]

这是我进行身份验证和接收twitterstream的操作:

private static  void listen() throws InterruptedException,TwitterException{

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setDebugEnabled(true)
        .setOAuthConsumerKey("*************")
        .setOAuthConsumerSecret("******************")
        .setOAuthAccessToken("*******************")
        .setOAuthAccessTokenSecret("************");

    Configuration configuration= configurationBuilder.build();
    TwitterStream twitterStream = new TwitterStreamFactory(configuration).getInstance();

    twitterStream.addListener(new twitter4j.StatusListener() {

        public void onStatus(Status status) {
            System.out.println("Status: {}"+ status);
        }

        public void onException(Exception ex) {
            System.out.println("Error callback"+ ex);
        }

        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {

        }

        public void onTrackLimitationNotice(int i) {

        }

        public void onScrubGeo(long l, long l1) {

        }

        public void onStallWarning(StallWarning stallWarning) {

        }

    });
    twitterStream.sample();
    TimeUnit.SECONDS.sleep(10);
    twitterStream.shutdown();
}

希望这可以帮助。 对我来说,关键是创建将配置对象传递给其构造函数的TwitterStreamFactory。 这样便可以进行身份​​验证。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM