实战 Groovy(1)-Twitter Search API
看一下 Twitter Search API 的在线文档(见 参考资料)。文档表明可以通过发出简单的 HTTP GET 请求搜索 Twitter。查询通过查询字符串中的 q 参数传递,结果以 Atom(一种 XML 联合格式)或 JavaScript Object Notation (JSON) 的形式返回。因此,要想以 Atom 的形式得到所有提到 thirstyhead 的条目,需要发出下面这样的 HTTP GET 请求:http://search.twitter.com/search.atom?q=thirstyhead。
如清单 1 所示,返回的结果是嵌套在 <feed> 元素中的一系列 <entry> 元素:
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom"> <entry> <title>thirstyhead: New series from Andrew Glover: Java Development 2.0 http://bit.ly/bJX5i</title> <content type="html">thirstyhead: New series from Andrew Glover: Java Development 2.0 http://bit.ly/bJX5i</content> <id>tag:twitter.com,2007: http://twitter.com/thirstyhead/statuses/3419507135</id> <published>2009-08-20T02:54:54+00:00</published> <updated>2009-08-20T02:54:54+00:00</updated> <link type="text/html" rel="alternate" href="http://twitter.com/thirstyhead/statuses/3419507135"/> <link type="image/jpeg" rel="image" href="http://s3.amazonaws.com/twitter_production/profile_images/ 73550313/flame_normal.jpg"/> <author> <name>ThirstyHead.com</name> <uri>http://www.thirstyhead.com</uri> </author> </entry> <entry>...</entry> <entry>...</entry> <!-- snip --></feed>
在 “实战 Groovy:构建和解析 XML” 中,可以看到很容易使用 Groovy 的 XmlSlurper 处理 XML 结果。既然了解了这些结果的形式,就来创建一个名为 searchCli.groovy 的文件,见清单 2:
if(args){ def username = args[0] def addr = "http://search.twitter.com/search.atom?q=${username}" def feed = new XmlSlurper().parse(addr) feed.entry.each{ println it.author.name println it.published println it.title println "-"*20 } }else{ println "USAGE: groovy searchCli <query>"}在命令行上输入 groovy searchCli thirstyhead,就会显示简洁的 Atom 结果,见清单 3:
$ groovy searchCli thirstyheadthirstyhead (ThirstyHead.com)2009-08-20T02:54:54ZNew series from Andrew Glover: Java Development 2.0 http://bit.ly/bJX5i--------------------kung_foo (kung_foo)2009-08-18T12:33:32ZThirstyHead interviews Venkat Subramaniam: http://blip.tv/file/2484840 "Groovy and Scala are good friends..." (via @mittie). very good.//snip
点击打开链接