In my last post I created a twitter developer account. In this post I will access Twitter with a Java program.
Setup Eclipse Project
Create a new Maven Project:
Create a simple project (skip archetype selection).
Change JRE System Library from Java 1.5 to Java 1.8.
Add Twitter4J to Maven dependencies:
4.0.0 de.kaulbach 1.0-SNAPSHOT jar 1.8 1.8 UTF-8 UTF-8 org.twitter4j twitter4j-stream 4.0.7
Configuration
Create a new file twitter4j.properties in folder src/main/resources with account properties from developer console:
oauth.consumerKey = // your key (API key) oauth.consumerSecret = // your secret (API secret key) oauth.accessToken = // your token oauth.accessTokenSecret = // your token secret
There are some other ways to configure (Java Code, Environment Variables, System Properties), see here
Java Code
Write a simple Code Example to show 7 Tweets with HashTag #Happy:
public class TwitterClient { public static void main(String[] args) throws Exception { Twitter twitter = TwitterFactory.getSingleton(); Query query = new Query("#Happy"); query.setCount(7); QueryResult result = twitter.search(query); for (Status status : result.getTweets()) { System.out.println("--"); System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText()); } System.out.println("----------------------------------------"); } }
Change code to show Tweets of Pope Francis with God in it:
Query query = new Query("from:Pontifex God");