Introduction to Twitter4J – Twitter4J简介

最后修改: 2017年 3月 11日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this article, we will have a look at using Twitter4J in a Java application to communicate with Twitter.

在这篇文章中,我们将看看如何在Java应用程序中使用Twitter4J来与Twitter通信。

2. Twitter4J

2.Twitter4J

Twitter4J is an open source Java library, which provides a convenient API for accessing the Twitter API.

Twitter4J是一个开源的Java库,它为访问Twitter API提供了方便的API。

Simply put, here’s how we can interact with the Twitter API; we can:

简单地说,这里我们可以与Twitter的API进行互动;我们可以。

  • Post a tweet
  • Get timeline of a user, with a list of latest tweets
  • Send and receive direct messages
  • Search for tweets and much more

This library ensures that we can easily do these operations, and it also ensures the security and privacy of a user – for which we naturally need to have OAuth credentials configured in our app.

这个库确保我们可以很容易地进行这些操作,它也确保了用户的安全和隐私–为此我们自然需要在我们的应用程序中配置OAuth凭证。

3. Maven Dependencies

3.Maven的依赖性

We need to start by defining the dependency for Twitter4J in our pom.xml:

我们需要先在pom.xml中定义Twitter4J的依赖关系。

<dependency>
    <groupId>org.twitter4j</groupId>
    <artifactId>twitter4j-stream</artifactId>
    <version>4.0.6</version>
</dependency>

To check if any new version of the library has been released – track the releases here.

要检查库的任何新版本是否已经发布–跟踪这里的发布情况

4. Configuration

4.配置

Configuring Twitter4J is easy and can be done in various ways – for example in a plain text file or a Java class or even using environment variables.

配置Twitter4J很简单,可以通过各种方式进行–例如在一个纯文本文件或一个Java类中,甚至使用环境变量。

Let’s look at each of these ways, one at a time.

让我们逐一看一下这些方式。

4.1. Plain Text File

4.1.纯文本文件

We can use a plain text file – named twitter4j.properties – to hold our configuration details. Let’s look at the properties which need to be provided:

我们可以使用一个纯文本文件–名为twitter4j.properties–来保存我们的配置细节。让我们来看看需要提供的属性。

oauth.consumerKey =       // your key
oauth.consumerSecret =    // your secret
oauth.accessToken =       // your token
oauth.accessTokenSecret = // your token secret

All these attributes can be obtained from Twitter Developer console after you make a new app.

所有这些属性都可以在你制作一个新的应用程序之后从Twitter开发者控制台获得。

4.2. Java Class

4.2. Java类

We can also use a ConfigurationBuilder class to configure Twitter4J programmatically in Java:

我们还可以使用ConfigurationBuilder类来在Java中以编程方式配置Twitter4J。

ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
  .setOAuthConsumerKey("your consumer key")
  .setOAuthConsumerSecret("your consumer secret")
  .setOAuthAccessToken("your access token")
  .setOAuthAccessTokenSecret("your access token secret");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();

Note that we’ll be using the Twitter instance in next section – when we start to fetch data.

注意,我们将在下一节使用Twitter实例–当我们开始获取数据时。

4.3. Environment Variables

4.3.环境变量

Configuring through environment variables is another choice we have. If we do that, note that we’ll need a twitter4j prefix in our variables:

通过环境变量进行配置是我们的另一个选择。如果我们这样做,请注意我们的变量中需要有twitter4j前缀。

$ export twitter4j.oauth.consumerKey =       // your key
$ export twitter4j.oauth.consumerSecret =    // your secret
$ export twitter4j.oauth.accessToken =       // your access token
$ export twitter4j.oauth.accessTokenSecret = // your access token secret

5. Adding / Retrieving Real-Time Tweet Data

5.添加/检索实时推特数据

With a fully configured application, we can finally interact with Twitter.

有了一个完全配置好的应用程序,我们终于可以与Twitter互动了。

Let’s look at few examples.

让我们看看几个例子。

5.1. Post a Tweet

5.1.发布推文

We’ll start by updating a tweet on Twitter:

我们先在推特上更新一条推文。

public String createTweet(String tweet) throws TwitterException {
    Twitter twitter = getTwitterinstance();
    Status status = twitter.updateStatus("creating baeldung API");
    return status.getText();
}

By using status.getText(), we can retrieve the tweet just posted.

通过使用status.getText(),我们可以检索到刚刚发布的tweet。

5.2. Get the Timeline

5.2.获取时间线

We can also fetch a list of tweets from the user’s timeline:

我们还可以从用户的时间轴上获取推文列表。

public List<String> getTimeLine() throws TwitterException {
    Twitter twitter = getTwitterinstance();
    
    return twitter.getHomeTimeline().stream()
      .map(item -> item.getText())
      .collect(Collectors.toList());
}

By using twitter.getHomeTimeline(), we get all tweets posted by the current account ID.

通过使用twitter.getHomeTimeline(),我们得到了当前账户ID发布的所有推文。

5.3. Send a Direct Message

5.3.发送直接信息

Sending and receiving a direct message to followers is also possible using the Twitter4j:

使用Twitter4j也可以向追随者发送和接收直接信息。

public static String sendDirectMessage(String recipientName, String msg) 
  throws TwitterException {
 
    Twitter twitter = getTwitterinstance();
    DirectMessage message = twitter.sendDirectMessage(recipientName, msg);
    return message.getText();
}

The sendDirectMessage method takes two parameters:

sendDirectMessage方法需要两个参数。

  • RecipientName: the twitter username of a message recipient
  • msg: message content

If recipient will not be found, the sendDirectMessage will throw an exception with exception code 150.

如果找不到收件人,sendDirectMessage将抛出一个异常代码150

5.4. Search for Tweets

5.4.搜索推文

We can also search for tweets containing some text. By doing this, we’ll get a list of tweets with the username of users.

我们还可以搜索包含一些文字的推文。通过这样做,我们会得到一个带有用户用户名的推文列表。

Let’s see how such a search can be performed:

让我们看看如何进行这样的搜索。

public static List<String> searchtweets() throws TwitterException {
 
    Twitter twitter = getTwitterinstance();
    Query query = new Query("source:twitter4j baeldung");
    QueryResult result = twitter.search(query);
    
    return result.getTweets().stream()
      .map(item -> item.getText())
      .collect(Collectors.toList());
}

Clearly, we can iterate over each tweet received in a QueryResult and fetch relative data.

显然,我们可以在QueryResult中迭代收到的每条tweet,并获取相对数据。

5.5. The Streaming API

5.5.流媒体API

Twitter Streaming API is useful when updates are required in real-time; it handles thread creation and listens to events.

Twitter Streaming API在需要实时更新时非常有用;它可以处理线程创建和监听事件。

Let’s create a listener which listens to tweet updates from a user:

让我们创建一个监听器,监听来自用户的推特更新。

public static void streamFeed() {

    StatusListener listener = new StatusListener() {

        @Override
        public void onException(Exception e) {
            e.printStackTrace();
        }
        @Override
        public void onDeletionNotice(StatusDeletionNotice arg) {
        }
        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
        }
        @Override
        public void onStallWarning(StallWarning warning) {
        }
        @Override
        public void onStatus(Status status) {
        }
        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }
    };

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();

    twitterStream.addListener(listener);

    twitterStream.sample();
}

We can put some println() statement to check the output tweet stream in all of the methods. All tweets have location metadata associated with it.

我们可以在所有的方法中放入一些println()语句来检查输出的tweet流。所有推文都有与之相关的位置元数据。

Please note that all the tweets data fetched by the API are in the UTF-8 format and since Twitter is a multi-language platform, some data format may be unrecognizable based upon its origin.

请注意,由API获取的所有推文数据都是UTF-8格式,由于Twitter是一个多语言平台,一些数据格式可能根据其来源而无法识别。

6. Conclusion

6.结论

This article was a quick but comprehensive introduction to using Twitter4J with Java.

这篇文章是对用Java使用Twitter4J的快速但全面的介绍。

The implementation of shown examples can be found on GitHub – this is a Maven based project, so it should be easy to import and run as it is. The only change we need to do is to insert our own OAuth credentials.

所示示例的实现可以在GitHub上找到 – 这是一个基于Maven的项目,所以应该很容易导入并按原样运行。我们需要做的唯一改变是插入我们自己的OAuth凭证。