Saturday, August 31, 2013

Get public tweets from twitter API in Android.

      Twitter provides you public tweets and simple authentication now. Twitter uses Client Credentials Grant flow of OAuth 2.0 specifications for their latest version.
First, you should get your Consumer key and Consumer secret from Twitter Developer site. This both works as sensitive passwords for your application.

1. Encode the both consumer key and consumer secret into set of credentials.
2. Make an request to POST oauth2/token. On successful, you will receive bearer token.
3. Attach screen name (twitterID) with your access token and get the data.

Encode Keys:

// URL encoding of consumer key.
String encodedConsumerKey = URLEncoder.encode("Your Consumer KEY here","UTF-8");

// URL encoding of consumer secret.    
String encodedConsumerSecret = URLEncoder.encode("Your Consumer Secret here","UTF-8");

//Concatenate the both strings with colon ':'.     
String authString = encodedConsumerKey +":"+encodedConsumerSecret;

//using base64 encode.    
String base64Encoded = Base64.encodeToString(authString.getBytes("UTF-8"), Base64.NO_WRAP);

Authentication: Get a Bearer Token

Request format for bearer token:

POST /oauth2/token HTTP/1.1
User-Agent: My Twitter App v1.0.23
Authorization: Basic " place here base64encoded string"
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 29
Accept-Encoding: gzip


Request Response:

HTTP/1.1 200 OK
Status: 200 OK
Content-Type: application/json; charset=utf-8
Content-Encoding: gzip
Content-Length: 140


The request must be in HTTP post and Authorization header contains value of  "Basic Base64 encoder string". There will be space between the Basic and base64 encoder string.
The Content -Type contains value like "application/x-www-form-urlencoded;charset=UTF-8" and grant_type should have value like "client_credentials".

Follow the below code to get the bearer token

//Use Http post to send request.
HttpClient httpclient = new DefaultHttpClient();
//Append twitter api url here.
String uriString = "";
HttpPost httppost = new HttpPost(uriString);
HttpParams httpParams = httppost.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 15000);
//Append EncodedString to Authorization Header.
httppost.setHeader("Authorization", "Basic " +base64EncodedString);
//Set Content type here.
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
HttpResponse response =null;

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();        
nameValuePairs.add(new BasicNameValuePair("grant_type", "client_credentials"));        
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));        
response = httpclient.execute(httppost);      
String returnedJsonStr = EntityUtils.toString(response.getEntity());

 int statusCode = response.getStatusLine().getStatusCode();
JSONObject jsonObject = new JSONObject(returnedJsonStr);
//Receive Bearer token here.
 receivedToken = jsonObject.getString("access_token");

On valid process, you will receive Access token here.

Get API requests with the bearer token:

Request Format:

GET /1.1/statuses/user_timeline.json?count=100&screen_name=twitterapi HTTP/1.1
User-Agent: My Twitter App v1.0.23
Accept-Encoding: gzip

The bearer token may be used to issue requests to API endpoints which support application-only auth.
The request includes the normal Https and Authorization header value contains like "Bearer space bearer-token" . Without twitter signing you can get the data.

Follow the below code for API requests:

HttpClient httpclient = new DefaultHttpClient();
//Append twitter count and screen name with api URL 
HttpGet httpget = new HttpGet(""+twitter_id); 
//Append bearer token here.
httpget.setHeader("Authorization", "Bearer "+ receivedToken);
HttpResponse response;
               //Receive response here and make it .
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null)
       InputStream instream = entity.getContent();
       twitter_response= convertStreamToString(instream);
       weets_array = new JSONArray(twitter_response);
       for (int i = 0; i < tweets_array.length(); i++)
            String texts = tweets_array.getJSONObject(i).getString("text");
            HashMap<String, String> map = new HashMap<String, String>();
            map.put(KEY_TWITTES, texts);
            JSONObject c = tweets_array.getJSONObject(0);
            JSONObject phone = c.getJSONObject("user");
            user_profile_pic_url = phone.getString("profile_image_url_https");
catch(Exception e)

Output ScreenShot:

Enjoy coding......

1 comment:

  1. Hi,
    I m using this concept but there is a rate limit problem which is 450request per 15 mnt
    and my application has more than 20000 downloads.Show m facing limit exceeded problem.Can you please tell me how to resolve this problem.