Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Java 

[Tutorial] Twitter + Java

Hi all,

Twitter4J is a Java library to interact with the Twitter API. With Twitter4J, you can integrate your Java application with Twitter services. If you have some knowledge of Java, implementing this library is quite simple; just add the jar to the Classpath environment variable of your Java Virtual Machine.
In this tutorial we will learn the basics about this API.

Features:
• Works on any Java platform version 1.4.2 or later.
• Works on the Android platform (as of version 2.1.0).
• Supports OAuth authentication.

Tweet from Java
To Tweet from Java we will use the following code:
Code
import java.util.List;
import twitter4j.*;

public class TwitterJ {

   private Twitter my_twitter;

   public TwitterJ(String userName, String password) {
       try {
           my_twitter = new Twitter(userName, password);
           my_twitter.verifyCredentials();
       } catch (TwitterException ex) {
           System.out.println("Error: "+ex.getMessage());
       }
   }

   public void newTweet(String tweet) {
       try {
           this.my_twitter.updateStatus(tweet);
       } catch (Exception ex) {
           System.out.println("Error: " + ex.getMessage());
       }
   }

   public static void main(String args[]){
       TwitterJ my_twitter = new TwitterJ("user", "password");
       my_twitter.newTweet("Tweet");
   }
}

Get your current status
Code
import java.util.List;
import twitter4j.*;

public class TwitterJ {

   private Twitter my_twitter;

   public TwitterJ(String userName, String password) {
       try {
           my_twitter = new Twitter(userName, password);
           my_twitter.verifyCredentials();
       } catch (TwitterException ex) {
           System.out.println("Error: "+ex.getMessage());
       }
   }


   public String getState(){
       String actualState = "";
       try {
           List<Status> statusList = my_twitter.getUserTimeline();
           actualState = String.valueOf(statusList.get(0).getText());
       } catch (TwitterException ex) {
           System.out.println("Error:"+ex.getMessage());
       }
       return "My state is: "+actualState;
   }



   public static void main(String args[]){
       TwitterJ my_twitter = new TwitterJ("user", "pass");
       System.out.println("State: "+my_twitter.getState());
   }
}

Regards

PS.: I would like that you add my post to the post where the Java source codes are located.


Possibly Related Threads...
Thread / Author Replies Views Last Post
[Java] by President HolyFeb 8, 2014 11:48 AM 3 193 Feb 8, 2014 11:48 AM
Last Post: Knautschtabak
[Java] by Canonsx130Dec 18, 2013 10:57 AM 21 1,161 Dec 18, 2013 10:57 AM
Last Post: leto12
[Java] by CatchMeIfYouCanOct 23, 2012 12:53 PM 6 444 Oct 23, 2012 12:53 PM
Last Post: redpois0n