Twitter REST API and Streaming API

Like my last blog, Twitter portlet of Liferay uses REST API. Twitter returns JSON Object, we just need to interpret it and store in our database. The bad thing for REST API is rate limit. In my previous blog, I mentioned that. For unauthenticated user, 150 per hour; authenticated user, 350 per hour. For a large website, it's not enough. The good news is we have another choice Streaming API. 

For my specific task, I just need to user streams. I also don't want to write from scratch because I don't know how to codeO(∩_∩)O~. Then I run into Twitter4jhttp://twitter4j.org/en/index.html. It has all APIs for REST API and Streaming API we want.  So actually we don't need to interpret JSON Object, we can ask Twitter4j do for us.

My task is: get real-time tweets and display in my own twitter portlet.

public class Test {
	
	public static void main(String[] args) {
		System.out.println("Start listening Twitter Streaming API....");
		TwitterStatusListener listener = context.getBean("twitterStatusListener",
				TwitterStatusListener.class);
		TwitterStream twitterStream = new TwitterStreamFactory().getInstance();

		twitterStream.addListener(listener);

		List<Feed> feeds = feedManager.getAllFeeds();//Here is to get Feeds which store twitterUserId.
		long[] followArray = new long[feeds.size()];
		for (int i = 0; i < feeds.size(); i++) {
			followArray[i] = feeds.get(i).getTwitterUserId();
		}
		twitterStream.filter(new FilterQuery(followArray)); //The FilterQuery just accepts long[] array of twitterUserids
	}

}
If you want to do more coding, go to look at twitter4j-example. It's very useful and clear. You can find at least one example for every API.

Another issue I run into is if we call  twitterStream.filter(new FilterQuery(followArray)); once, it'll set up a new connection for us. Streaming API is used for a long-live connection, If we disconnect and reconnect frequently, our project will also hit rate limit. 发火抓狂快哭了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值