Twitter社区网络和微博客服务自2006年推出以来,已经深受大家欢迎。Twitter用户可以通过SMS(Short Message Service),RSS或者是Twitter应用程序来发送自己的tweets(一种即时的,最多可达到140个字符的文本信息),或者阅读其他人的tweets。tweets 在用户的个人资料页面上显示,并传送给那些已经注册的用户。在这篇文章中,你将会学到如何创建自己的twitter服务(通过twitter API访问tweets,并以pdf的形式保存tweets)。
你将通过三个开源java类库来创建你的twitter应用程序:
1,Apache Commons 类库的 HttpClient3.x,用这个类库,你可以从twitter api 获得一个xml流形式的tweet和Common logging ,Codec组件。
2,dom4j,用来解析xml并从中抽取tweet。
3,iText用来创建pdf文件。
这个教程里有实际例子,所以如果你还没有做这些的话,先下载这三个类库。同时,我也会在接下来讲述的过程中,不断提醒你需要什么jar包。如果你还没有注册的话,那就先注册一个吧,以便你有可以利用的tweets。
你将从建立一个独立的java 程序开始twitter应用程序的书写。最终,你需要把java程序整合到servlet中,以便能够把它放到你的站点上并提供给其他的Twitterati。
Getting Started:
每一个twitter application 都利用了 Twitter API wiki 上的Twitter API ,假设现在你只对访问他感兴趣,你想通过某种方式来取回并且具体化这些tweets。你还不知道你将制作一个pdf文档,你只知道要“消费”一定数量的tweets。所以你要通过写这样一个消费者接口来开始书写你的application。如下:
Code
import org.dom4j.Element;
public interface TweetConsumer {
public String tweet(Element element) throws TweetException;
}
Twitter API可以通过xml,json,rss来提供tweets。在这个例子中,你将选择xml,并通过dom4j来解析xml,不要忘了把dom4j jar包添加到你的环境变量中,你将引入org.dom4j.Element接口,这个xml元素包含大量的信息:一个时间,一些文字,一个用户号,还有一个tweet号,这个tweet号就是你用作tweet()方法的返回值的一个字符串。在出错的时候,你还要抛出一个TweetException。
Code
public class TweetException extends Exception {
private static final long serialVersionUID = 7577136074623618615L;
public TweetException(Exception e) {
super(e);
}
}
Connecting to the twitter API:
首先,在环境变量中加入commons-httpclient.jar, commons-codec.jar, and commons-logging.jar,这些是从Apache Commons project中得到的,这些jar包将帮助你建立和twitter API的连接,下面要介绍的是TweetProducer类,他是用来获取一个用户的tweets的类。
Code
public class TweetProducer {
protected HttpClient client;
protected TweetConsumer consumer;
public void createClient(String username, String password) {
client = new HttpClient();
client.getState().setCredentials(
new AuthScope("twitter.com", 80, AuthScope.ANY_REALM),
new UsernamePasswordCredentials(username, password));
client.getParams().setAuthenticationPreemptive(true);
}
public void setConsumer(TweetConsumer consumer) {
this.consumer = consumer;
}
public String execute(String since_id) throws TweetException {
String id = null;
String tmp;
GetMethod get = new GetMethod("http://twitter.com/statuses/friends_timeline.xml");
if (since_id != null && since_id.length() > 0) {
get.setQueryString("?count=200&since_id=" + since_id);
}
else {
get.setQueryString("?count=200");
}
get.setDoAuthentication(true);
try {
client.executeMethod(get);
SAXReader reader = new SAXReader();
Document document = reader.read(get.getResponseBodyAsStream());
Element root = document.getRootElement();
for (Iterator i = root.elementIterator(); i.hasNext(); ) {
tmp = consumer.tweet((Element)i.next());
if (id == null) id = tmp;
}
} catch (HttpException e) {
throw new TweetException(e);
} catch (IOException e) {
throw new TweetException(e);
} catch (DocumentException e) {
throw new TweetException(e);
} finally {
get.releaseConnection();
}
return id;
}
}
这个类中有三个方法:
createClient()方法:用于创建一个HttpClient对象,你必须登录后才能得到你跟踪的人的tweets。所以你必须得提供你的用户名和密码。Twitter用HTTP Basic Authentication,在创建HttpClient对象后,你将拥有优先认证权。
setConsumer()方法:你将从一个TweetConsumer 到the TweetProducer。你正在应用一个接口,因为在这个时候,你可能还没有决定怎样送出你的tweets。
execute()方法:实际做工作的方法。他接受一个id 并且返回一个id。下面让我们看看他是怎样工作的。
获取tweets:
标准的通过twitter API获取tweets的方法是get()方法。你想获得一个特定用户的状态,(状态是tweets的另一种说法)你想得到tweets并把他们放到一个xml文件里。想达到这个目的,你需要GetMethod对象。
Code
GetMethod get = new GetMethod("http://twitter.com/statuses/friends_timeline.xml");
如果你执行这个方法,你将得到包含20个已认证用户的最新状态的xml文件,你可以通过page参数获得更多,最多可以达到160个,包含3200个状态,在这个演示实例中,你还可以通过count参数具体指定你想获得的状态的个数,默认是20个,最多是200个,最好使用count的另外一个原因是你不能非法利用twitter多次访问服务器。
另外一个可选参数是since_id,每一个状态或者tweet拥有一个id,如果你选择用since_id,他将返回一个比指定id更新的id,如果你选择这样一个id,你的TweetProduce将按如下方式设置查询字符串。
Code
get.setQueryString("?count=200&since_id=" + since_id);
一旦查询字符串被设定,你可以执行以下的查询:
Code
client.executeMethod(get);
现在,你可以通过获得根节点来把response放到SAXReader中,
Code
SAXReader reader = new SAXReader();
Document document = reader.read(get.getResponseBodyAsStream());
Element root = document.getRootElement();
最后,你可以循环迭代每一个节点:
Code
for (Iterator i = root.elementIterator(); i.hasNext(); ) {
tmp = consumer.tweet((Element)i.next());
if (id == null) id = tmp;
}
可以看到,你获得的第一个tweet就是最近的一个,你把这个tweet的id放到了id变量中,而他就是execute()方法的返回值。
到目前为止,一切顺利。但是,main方法在那里呢?怎么才能测试这些代码呢?或许在你生成pdf文档之前,你要写一些简单的东西。
我的第一个 TweetConsumer:
你已经写了一个TweetProducer类,但是现在你没办法测试他,因为你还没有实现TweetProducer接口,下面的代码是把xml发送到System.out,你可以用这段代码找到在Twitter API提供的xml中到底包含了什么。
Code
public class SystemOutTweets implements TweetConsumer {
public String tweet(Element tweet) {
System.out.println(tweet.asXML());
return tweet.elementText("id");
}
public static void main(String[] args) throws TweetException {
TweetProducer t = new TweetProducer();
t.createClient("bruno1970", "myfakepassword");
t.setConsumer(new SystemOutTweets());
System.out.println("Start tweeting:");
String id = t.execute(null);
System.out.println("The End; last tweet: " + id);
}
}
如果你把bruno1970(我的用户号)和我的密码替换成为你自己的,你将会得到你的包含200个状态得节点,
下面的代码是一个非常好的例子,他会让rrradiogirrrl对他的追随者说:"Hello! Good morning!"
Code
<status>
<created_at>Thu Jan 29 07:01:55 +0000 2009</created_at>
<id>1157836999</id>
<text>Hello! Good morning!</text>
<source><a href="http://www.ping.fm/">Ping.fm</a></source>
<truncated>false</truncated>
<in_reply_to_status_id/>
<in_reply_to_user_id/>
<favorited>false</favorited>
<in_reply_to_screen_name/>
<user>
<id>9737242</id>
<name>Sigrid</name>
<screen_name>rrradiogirrrl</screen_name>
<location>Belgium</location>
<description>happy,internet addict,radio geeky, web 2.0 fan, reader, jr. product manager @ a Belgian television channel</description>
<profile_image_url>http://s3.amazonaws.com/twitter_production/profile_images/58441671/nospam_gmail.com_cbf8aad8_normal.jpg</profile_image_url>
<url>http://www.sigridschrijft.be/blog</url>
<protected>false</protected>
<followers_count>465</followers_count>
</user>
</status>
当然,在我的例子里,将输出:The End; last tweet: 1158488197
所以我把null换成1158488197
Code
t.execute("1158488197");
但是不幸的是,我没有得到200个状态,我只得道了9个,这说明在我执行systemout的时候我的追随的Twitterati发送了9个
tweets到twitter,当然,twitter很高兴,因为我用了很少的带宽,而,我也很高兴,因为我不需要重复读tweets。
未完待续。。。。。。。。。
这是在http://www.javaworld.com/javaworld/jw-03-2009/jw-03-write-your-own-twitter-app.html?page=1
上面的一篇关于twitter api 的介绍。