En uno de nuestros proyectos de Turismo Rural, hemos tenido que integrar Twitter en la aplicación web y para ello hemos empleado la API Twitter4J. Aquí os dejamos una pequeña introducción a la librería Twitter4J y OAuth.
Primero deberemos registrar la aplicación en la sección de desarrollo de Twitter, es decir en http://dev.twitter.com:
Creamos el registro de la aplicación:
Ahora ya disponemos de los datos para poder trabajar con Twitter4J (token y tokenSecret):
El proyecto requiere de las librerías que se incluyen en el proyecto Twitter4J y además las librerías de commons-logging o las de SL4J.
A continuación, mostramos parte de la clase para acceder a Tiwitter:
package es.neodoo.twitter;
import java.util.List;
import twitter4j.AccountTotals;
import twitter4j.DirectMessage;
import twitter4j.Paging;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.ResponseList;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
public class TwitterService {
private Twitter twitter;
public TwitterService(String token, String tokenSecret) {
TwitterFactory factory = new TwitterFactory();
AccessToken accessToken = new AccessToken(token,
tokenSecret);
this.twitter = factory.getInstance(accessToken);
}
public List searchTweets(String query) throws TwitterException {
QueryResult result = twitter.search(new Query(query));
List tweets = result.getTweets();
return tweets;
}
}
Y la clase principal para probarlo:
package es.neodoo.twitter;
import java.util.Date;
import java.util.List;
import twitter4j.AccountTotals;
import twitter4j.DirectMessage;
import twitter4j.GeoLocation;
import twitter4j.Place;
import twitter4j.Tweet;
import twitter4j.TwitterException;
public class TwitterMain {
/**
* @param args
*/
public static void main(String[] args) {
String token = "
277181746-i5plkIhZlZfszXdNnVFtZ2X8fB2duyBn79eDHTUM
"; String tokenSecret = "
yGVTgEBNwCbMtGkbi2Qz1dR51mZLsKzPmJJOUUrYvDU
";
TwitterService ts = new TwitterService(token, tokenSecret);
List tweets;
try {
tweets = ts.searchTweets("ruralbook");
for (Tweet tweet : tweets) {
// System.out.println("@" + tweet.getFromUser() + " - "
// + tweet.getText());
System.out.print("!!! Twit !!! ");
Date createdAt = tweet.getCreatedAt();
String user = tweet.getFromUser();
long userId = tweet.getFromUserId();
double latitud = -1, longitud = -1;
try {
GeoLocation geoLocation = tweet.getGeoLocation();
latitud = geoLocation.getLatitude();
longitud = geoLocation.getLongitude();
} catch (Exception e) {
}
long id = tweet.getId();
String isoLanguageCode = tweet.getIsoLanguageCode();
String location = tweet.getLocation();
Place place = tweet.getPlace();
Place[] containedWithIn = null;
String country = null;
String url = null;
String fullName = null;
GeoLocation[][] boundingBoxCoordinates = null;
String geometryType = null;
String idPlace = null;
String name = null;
String placeType = null;
String streetAddress = null;
String urlPlace = null;
try {
containedWithIn = place.getContainedWithIn();
country = place.getCountry();
url = place.getCountryCode();
fullName = place.getFullName();
boundingBoxCoordinates = place.getBoundingBoxCoordinates();
geometryType = place.getGeometryType();
idPlace = place.getId();
name = place.getName();
placeType = place.getPlaceType();
streetAddress = place.getStreetAddress();
urlPlace = place.getURL();
} catch (Exception e) {
}
String profileImageUrl = tweet.getProfileImageUrl();
String text = tweet.getText();
String source = tweet.getSource();
String toUser = tweet.getToUser();
long toUserId = tweet.getToUserId();
System.out.println("createdAt: " + createdAt + ", " + "user: "
+ user + "," + "userId: " + userId + "," + "latitud: "
+ latitud + "," + "longitud: " + longitud + ","
+ "id: " + id + "," + "isoLanguageCode: "
+ isoLanguageCode + "," + "location: " + location + ","
+ "place: " + place + "," + "containedWithIn: "
+ containedWithIn + "," + "country: " + country + ","
+ "url: " + url + "," + "fullName: " + fullName + ","
+ "boundingBoxCoordinates: " + boundingBoxCoordinates
+ "," + "geometryType: " + geometryType + ","
+ "idPlace: " + idPlace + "," + "name: " + name + ","
+ "placeType: " + placeType + "," + "streetAddress: "
+ streetAddress + "," + "urlPlace: " + urlPlace + ","
+ "profileImageUrl: " + profileImageUrl + ","
+ "text: " + text + "," + "source: " + source + ","
+ "toUser: " + toUser + "," + "toUserId: " + toUserId);
}
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Fijaros que las cadenas token y tokenSecret deben coincidir con las que se generan al inscribir la aplicación en el twitter.
Existe una forma adicional en la que se piden los parámetros Access Token y Access Token Secret pero no lo contemplamos en este apartado.



estuve probando tu código pero me sale un error que no existe la librería import twitter4j.Tweet; dentro de twitter4j, no se si me puedes dar mas alcance sobre esta librería.
muchas gracias.
Hola Gilmert,
Ahora mismo no recuerdo con que versión de librería de Twitter4J (http://twitter4j.org) lo implementé.
Vete a https://github.com/yusuke/twitter4j/releases y por las fechas de la publicación del post, utilizaría las librerías 2.1.x o 2.2.x por ser del año 2011.
Ya me dirás. Suerte!