Quelle API devrais-je utiliser pour obtenir les tweets 'n' récents d'un utilisateur particulier avec un compte public?
Pour obtenir les tweets d'un utilisateur spécifique, utilisez la méthode GET statuses/user_timeline API.
5 derniers tweets avec le code PHP.
$tweets_result=file_get_contents("https://api.Twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=username&count=5");
$data=json_decode($tweets_result);
print_r($data);
Nous pouvons utiliser l’API Twitter Rest pour obtenir les tweets d’un utilisateur donné. Vous pouvez télécharger la source de Afficher les tweets d’un utilisateur particulier sous Android
activity_main.xml
<RelativeLayout Android:layout_width="match_parent"
Android:layout_height="match_parent"
xmlns:Android="http://schemas.Android.com/apk/res/Android" >
<RelativeLayout
Android:layout_width="match_parent"
Android:layout_height="40dp"
Android:id="@+id/rl_menu"
Android:background="@color/colorPrimaryDark">
<TextView
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:text="Twitter Tweets"
Android:textColor="#ffffff"
Android:textSize="15dp"
Android:layout_centerInParent="true"/>
</RelativeLayout>
<ListView
Android:layout_width="match_parent"
Android:id="@+id/lv_list"
Android:layout_height="match_parent"
Android:layout_below="@+id/rl_menu"></ListView>
</RelativeLayout>
MainActivity.Java
package com.gettweets;
import Android.app.Activity;
import Android.app.ListActivity;
import Android.app.ProgressDialog;
import Android.content.Context;
import Android.net.ConnectivityManager;
import Android.net.NetworkInfo;
import Android.os.AsyncTask;
import Android.os.Bundle;
import Android.util.Base64;
import Android.util.Log;
import Android.widget.ArrayAdapter;
import Android.widget.ListView;
import Android.widget.Toast;
import com.google.gson.Gson;
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 org.json.JSONArray;
import org.json.JSONObject;
import Java.io.*;
import Java.net.URLEncoder;
import Java.util.ArrayList;
/**
* Demonstrates how to use a Twitter application keys to access a user's timeline
*/
public class MainActivity extends Activity {
final static String ScreenName = "Deepshikhapuri";
final static String LOG_TAG = "rnc";
ListView lv_list;
ArrayList<String> al_text = new ArrayList<>();
Adapter obj_adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv_list = (ListView)findViewById(R.id.lv_list);
downloadTweets();
}
// download Twitter timeline after first checking to see if there is a network connection
public void downloadTweets() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadTwitterTask().execute(ScreenName);
} else {
Toast.makeText(getApplicationContext(),"Please check your internet connection",Toast.LENGTH_SHORT).show();
}
}
// Uses an AsyncTask to download a Twitter user's timeline
private class DownloadTwitterTask extends AsyncTask<String, Void, String> {
final static String CONSUMER_KEY = "nW88XLuFSI9DEfHOX2tpleHbR";
final static String CONSUMER_SECRET = "hCg3QClZ1iLR13D3IeMvebESKmakIelp4vwFUICuj6HAfNNCer";
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=";
final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setTitle("Loading");
dialog.setMessage("Please wait");
dialog.show();
}
@Override
protected String doInBackground(String... screenNames) {
String result = null;
if (screenNames.length > 0) {
result = getTwitterStream(screenNames[0]);
}
return result;
}
// onPostExecute convert the JSON results into a Twitter object (which is an Array list of tweets
@Override
protected void onPostExecute(String result) {
Log.e("result",result);
dialog.dismiss();
try {
JSONArray jsonArray_data = new JSONArray(result);
al_text.clear();
for (int i=0; i<jsonArray_data.length();i++){
JSONObject jsonObject = jsonArray_data.getJSONObject(i);
al_text.add(jsonObject.getString("text"));
}
}catch (Exception e){
e.printStackTrace();
}
// send the tweets to the adapter for rendering
obj_adapter= new Adapter(getApplicationContext(), al_text);
lv_list.setAdapter(obj_adapter);
}
// convert a JSON authentication object into an Authenticated object
private 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) {
// just eat the exception
}
}
return auth;
}
private 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();
}
private 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;
}
}
}
Authenticated.Java Package com.gettweets;
public class Authenticated {
String token_type;
String access_token;
}
adapter_layout.xml
<RelativeLayout Android:layout_width="match_parent"
Android:layout_height="match_parent"
xmlns:Android="http://schemas.Android.com/apk/res/Android">
<TextView
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:id="@+id/tv_text"
Android:textSize="18dp"
Android:layout_margin="10dp"
Android:textColor="#000000"/>
</RelativeLayout>
Adaptateur.Java
package com.gettweets;
import Android.content.Context;
import Android.graphics.Typeface;
import Android.util.Log;
import Android.view.LayoutInflater;
import Android.view.View;
import Android.view.ViewGroup;
import Android.widget.ArrayAdapter;
import Android.widget.TextView;
import Java.text.SimpleDateFormat;
import Java.util.ArrayList;
import Java.util.Calendar;
import Java.util.Date;
public class Adapter extends ArrayAdapter<String> {
Context context;
ViewHolder viewHolder;
ArrayList<String> al_newslist=new ArrayList<>();
public Adapter(Context context, ArrayList<String> al_newslist) {
super(context, R.layout.adapter_layout, al_newslist);
this.al_newslist=al_newslist;
this.context=context;
}
@Override
public int getCount() {
Log.e("ADAPTER LIST SIZE",al_newslist.size()+"");
return al_newslist.size();
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public int getViewTypeCount() {
if (al_newslist.size() > 0) {
return al_newslist.size();
} else {
return 1;
}
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.adapter_layout, parent, false);
viewHolder.tv_name = (TextView) convertView.findViewById(R.id.tv_text);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv_name.setText(al_newslist.get(position));
return convertView;
}
private static class ViewHolder {
TextView tv_name;
}
}