Program Resource

Resource libraries for programmers and developers

(June 12, 2013) Due to end of service, code below no longer works.

Easy code to get specific user’s tweet. This API has a restriction, that max number of API calls allowed from same IP is limited to 150 times per hour. Therefore, users who share global IP will easily result in 400 (Bad Request).

May be usable for personal use.

public void init_fetch_tweet(String tweet_user_id,int tweet_num) {

	String url="http://api.twitter.com/1/statuses/user_timeline.json?screen_name="+tweet_user_id+"&count="+tweet_num;
	StringBuffer sb=new StringBuffer();

	try{
		int responseCode = 0;
		String defaultUA = "MyMato/1.0 (Linux; U; Android 2.1; en-us) AppleWebKit/522+ (KHTML, like Gecko) Safari/419.3";
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse httpResponse = null;

		httpClient.getParams().setParameter("http.connection.timeout", new Integer(10000));
		HttpParams params1 = httpClient.getParams();
		params1.setParameter(HttpProtocolParams.USER_AGENT, defaultUA);
		HttpConnectionParams.setConnectionTimeout(params1, 10000);
		HttpConnectionParams.setSoTimeout(params1, 10000);
		httpResponse = httpClient.execute(httpGet);
		responseCode = httpResponse.getStatusLine().getStatusCode();

		if (responseCode == HttpStatus.SC_OK) {
			InputStream istream = httpResponse.getEntity().getContent();
			InputStreamReader reader = new InputStreamReader(istream);
			BufferedReader objBuf = new BufferedReader(reader);
			StringBuilder builder = new StringBuilder();
			String sLine;
			while((sLine = objBuf.readLine()) != null){
				builder.append(sLine);
			}
			String r = builder.toString();
			istream.close();

			JSONArray array = new JSONArray(r);
			for(int i=array.length()-1; i>=0; i--){
				Object obj=array.get(i);
				if( obj instanceof JSONObject ){
					Object text = ((JSONObject)obj).get("text");
					Object time = ((JSONObject)obj).get("created_at");
					String subtime = time.toString();
					String tweetitem = (tweet_user_id+":"+text.toString()+"("+subtime.substring(0,subtime.indexOf("+"))+")",this);
					//tweetitem holds sinlge tweet
				}
			}
		}else{
			if (responseCode == 400)
				cdata.notice_appendtext("Failed to fetch Tweet (code:"+responseCode+" might be restriction",this);
			else
				cdata.notice_appendtext("Failed to fetch Tweet (code:"+responseCode+")",this);
		}
	}
	catch(Exception ex){
		cdata.notice_appendtext("Failed to fetch tweet ("+ex.getMessage()+")",this);
	}
}
Print Friendly, PDF & Email

This post is also available in: Japanese

Leave a Reply

Your email address will not be published. Required fields are marked *


*

CAPTCHA