Twitter API – Tutorial


 

To create a twitter app, the first thing you need to do to get your Twitter API key is to create a Twitter application through their site. Visit dev.twitter.com/apps and login to your Twitter account. Then, just fill out the basic information for the application and it’s ready to be published.

Twitter API

Name – This field will be the display name of your application and will be used during user authentication. It will be checked against all other Twitter applications, so make sure to use a unique name.

Description – Write a short description on what you intend to do with the application.

Website – Fill in the full URL (including http://www) of the website you intend to either use the application or make it available for public download.

Callback URL – If you intend to return your users to a specific URL after authentication, specify it here. In basic cases like WordPress widget integration, this field can be left blank.

Read and agree to the Developer Rules of the Road, enter the Captcha phrase, and create! You’re now done creating your application, that wasn’t so hard was it?

Now that you’ve created your application, Twitter has assigned you a few data points to work with.

Twitter API

You must create a personal Access Token and Secret key to allow you to unlock personal account functions with your application – just click ‘Create Access Token’ and Twitter will add these data points as well.

If your application requires additional functionality, you can increase the default Access Level from Read-only to Read-Write or even Read-Write-DirectMessage. If you’re creating an application that only needs to pull tweets, Read-only is all you need.

In basic cases like WordPress widget integration, all you’ll likely need are the Consumer Key & Secret with the Access Token & Secret. These API keys let Twitter know that you’re a registered Twitter user that has a certain level of access to their API, so keep these keys secret.

Now you’re all set to create your Twitter Application in order to get your API Key.

1. Create a Android Project.
Create a Parser Class which facilitates the functionality of the parsing the Twitter Time Line Feed.

Parser.java
package org.aynsoft.java;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import android.util.Base64;
import com.google.gson.Gson;
public class Parser {

	final static String CONSUMER_KEY = "YOUR CONSUMER KEY";
	final static String CONSUMER_SECRET = "YOUR CONSUMER SECRET KEY";
	final static String TwitterTokenURL = "https://api.twitter.com/oauth2/token";
	final static String TwitterStreamURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";

	public Parser() {		
	}
	
	// converts a string of JSON data into a Twitter object
	public Twitter jsonToTwitter(String result) {
		Twitter twits = null;
		if (result != null && result.length() > 0) {
			try {
				Gson gson = new Gson();
				twits = gson.fromJson(result, Twitter.class);
			} catch (IllegalStateException ex) {
				// just eat the exception
			}
		}
		return twits;
	}

	// convert a JSON authentication object into an Authenticated object
	public Authenticated jsonToAuthenticated(String rawAuthorization) {
		Authenticated auth = null;
		if (rawAuthorization != null && rawAuthorization.length() > 0) {
			try {
				Gson gson = new Gson();
				auth = gson.fromJson(rawAuthorization, Authenticated.class);
			} catch (IllegalStateException ex) {
				ex.printStackTrace();
			}
		}
		return auth;
	}

	public String getResponseBody(HttpRequestBase request) {
		StringBuilder sb = new StringBuilder();
		try {

			DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
			HttpResponse response = httpClient.execute(request);
			int statusCode = response.getStatusLine().getStatusCode();
			String reason = response.getStatusLine().getReasonPhrase();

			if (statusCode == 200) {

				HttpEntity entity = response.getEntity();
				InputStream inputStream = entity.getContent();

				BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
				String line = null;
				while ((line = bReader.readLine()) != null) {
					sb.append(line);
				}
			} else {
				sb.append(reason);
			}
		} catch (UnsupportedEncodingException ex) {
		} catch (ClientProtocolException ex1) {
		} catch (IOException ex2) {
		}
		return sb.toString();
	}

	public  String getTwitterStream(String screenName) {
		String results = null;

		// Step 1: Encode consumer key and secret
		try {
			// URL encode the consumer key and secret
			String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
			String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");

			// Concatenate the encoded consumer key, a colon character, and the
			// encoded consumer secret
			String combined = urlApiKey + ":" + urlApiSecret;

			// Base64 encode the string
			String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);

			// Step 2: Obtain a bearer token
			HttpPost httpPost = new HttpPost(TwitterTokenURL);
			httpPost.setHeader("Authorization", "Basic " + base64Encoded);
			httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
			httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
			String rawAuthorization = getResponseBody(httpPost);
			Authenticated auth = jsonToAuthenticated(rawAuthorization);

			// Applications should verify that the value associated with the
			// token_type key of the returned object is bearer
			if (auth != null && auth.token_type.equals("bearer")) {

				// Step 3: Authenticate API requests with bearer token
				HttpGet httpGet = new HttpGet(TwitterStreamURL + screenName);

				// construct a normal HTTPS request and include an Authorization
				// header with the value of Bearer <>
				httpGet.setHeader("Authorization", "Bearer " + auth.access_token);
				httpGet.setHeader("Content-Type", "application/json");
				// update the results with the body of the response
				results = getResponseBody(httpGet);
			}
		} catch (UnsupportedEncodingException ex) {
		} catch (IllegalStateException ex1) {
		}
		return results;
	}
}

2.Use this parser class to Download feeds from server using the AsycTask.

MainActivity.java
package org.aynsoft.timeLine;

import org.aynsoft.java.InternetConnection;
import org.aynsoft.java.Parser;
import org.aynsoft.java.Twitter;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends Activity {

	final static String ScreenName = "User_name";//user name of the usee
	final static String LOG_TAG = "ayn";
	private Parser parser;
	public static Twitter tweets;

	//Run when activity first create
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		parser=new Parser();	
		//download the tweets
		downloadTweets();
	}

	public void downloadTweets() {
		//check for the internet connection
		if (InternetConnection.checkNetworkConnection(getBaseContext())) {
			new DownloadTwitterTask().execute(ScreenName);
		} else {
			//Fires a toast and finish itself
			Toast.makeText(getBaseContext(), "No Internet Connection",
					Toast.LENGTH_SHORT).show();
			finish();
		}
	}

	private class DownloadTwitterTask extends AsyncTask<String, Void, String> {		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			
		} 
		@Override
		protected String doInBackground(String... screenNames) {
			String result = null;
			if (screenNames.length > 0) {
				result = parser.getTwitterStream(screenNames[0]);
			}			
			return result;
		}
		@Override
		protected void onPostExecute(String result) {
			tweets = parser.jsonToTwitter(result);				
			//Tweets are ready do whatever
		}
	}
}

We have considerable experience in developing apps using Twitter API.

Over the years we have developed several advanced Twitter based Android and iPhone components, code modules and Frameworks that can work as plug and play solutions for developing new apps that will substantially reduce the app development cost and time.

Contact us to discuss your Twitter based mobile application development project

Posted in All Tutorials, Android Tutorials | Tagged | Leave a comment

Leave a Reply

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

Powered By: wpnova.com