使用 Twitter API 获取特定用户最近的推文

42
我需要使用哪个API才能获取一个公开账户特定用户的最近'n'条推文?

2
你使用的是哪种编程语言? - Tim
1
这里有一个链接,你可以找到使用 Twitter 1.1 API 选择推文的代码示例:https://dev59.com/82cs5IYBdhLWcg3wXSuU - lackovic10
1
如果您@user330973再次上线,您应该更改此问题的正确答案,以便未来使用 :) - Jimbo
5个回答

30

10
这种方法尚未被弃用。 - abraham
这个 API 是否有返回推文数量的限制? - sharon182
1
此方法只能返回用户最近的3200条推文。 - abraham

13
截至2013年5月7日,Twitter已经废弃了v1.0,并退役,v1.1是唯一访问API的方法,需要使用OAuth进行身份验证的请求。

v1.0 deprecated

这意味着您无法仅仅使用PHP的file_get_contents()来抓取此类内容 - 您需要编写一个利用OAuth和Twitter v1.1 API的脚本。

我最近在Stack Overflow上写了一篇答案,帮助新手使用Twitter v1.1 API,并编写了一个类,使其更加简便。

您需要创建开发人员帐户,获取一组用于应用程序中的开发人员密钥,并使用OAuth进行身份验证请求。如果您阅读上面的帖子,您将看到我创建了一个简单的类,允许您这样做。

TLDR: 不能再使用v1.0,使用1.1和此类以简化操作: https://github.com/J7mbo/twitter-api-php


你可以使用file_get_contents和OAuth。 - hakre
短板也在你的Github类中。愚蠢的curl,如果有file_get_contents就不需要它;)(首先将那个错误消息修复为有用的东西,我想说) - hakre
哈哈!嘿,它能胜任工作 :P @hakre告诉我你的建议? - Jimbo
@Jimbo:你好,我正在使用 https://api.twitter.com/1/statuses/user_timeline.json?include_rts=true&screen_name=mehuljoisar&count=50 API 通过传递 screen_name 来获取任何用户的公共推文。在 Twitter API v1 的退役后,如 https://dev.twitter.com/blog/api-v1-retirement-final-dates 所建议的那样,它还能继续工作吗? - Mehul Joisar
1
@MehulJoisar 从现在开始,您需要使用经过身份验证的请求,并且还需要使用版本1.1(而不是您当前使用的版本1)。GET状态/用户时间线的文档显示需要oath。所有1.0调用都将停止工作,因此您需要使用我的类并注册一些开发密钥(请参见我上面链接的帖子)。1.1中statuses/user_timeline的文档:dev.twitter.com/docs/api/1.1/get/statuses/user_timeline - Jimbo

6
用PHP代码获取最新的5条推文。
$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);

20
注意:由于OAuth和v1.1 API的原因,此方法不再适用。 - Jimbo

1
我们可以使用 Twitter Rest API 获取特定用户的推文。您可以下载 在 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 包 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>

Adapter.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;



    }

}

0

要获取特定 Twitter 帐户的推文,您可以使用 Twitter API v2 中添加的新 用户推文时间线 API 方法。


1
目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接