简体   繁体   English

在API v1.1中使用JSON从Twitter上获取推文

[英]Fetching tweets from twitter using JSON in API v1.1

The Twitter REST API v1 is no longer active.What modification I need to make to run this code in API v1.1.Here is my code for fetching tweets from twitter from particular uri which was used for API v1 - Twitter REST API v1不再处于活动状态,需要进行哪些修改才能在API v1.1中运行此代码,这是我的代码,用于从特定的uri提取来自twitter的推文中的推文,该推文用于API v1-

public class TwitterFeedActivity extends ListActivity {
        private ArrayList<Tweet> tweets = new ArrayList<Tweet>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        new MyTask().execute();

    }

      private class MyTask extends AsyncTask<Void, Void, Void> {
              private ProgressDialog progressDialog;

              protected void onPreExecute() {
                      progressDialog = ProgressDialog.show(TwitterFeedActivity.this,
                                        "", "Loading. Please wait...", true);
              }

              @Override
              protected Void doInBackground(Void... arg0) {
                      try {

                              HttpClient hc = new DefaultHttpClient();
                              HttpGet get = new
                              HttpGet("http://search.twitter.com/search.json?q=android");

                              HttpResponse rp = hc.execute(get);

                              if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
                              {
                                      String result = EntityUtils.toString(rp.getEntity());
                                      JSONObject root = new JSONObject(result);
                                      JSONArray sessions = root.getJSONArray("results");
                                      for (int i = 0; i < sessions.length(); i++) {
                                              JSONObject session = sessions.getJSONObject(i);

                                      Tweet tweet = new Tweet();
                                               tweet.content = session.getString("text");
                                               tweet.author = session.getString("from_user");
                                               tweets.add(tweet);
                                      }
                             }
                     } catch (Exception e) {
                             Log.e("TwitterFeedActivity", "Error loading JSON", e);
                     }
                     return null;

        }
        @Override
        protected void onPostExecute(Void result) {
                progressDialog.dismiss();
                setListAdapter(new TweetListAdaptor(
                                TwitterFeedActivity.this, R.layout.list_item, tweets));
         }

    }

    private class TweetListAdaptor extends ArrayAdapter<Tweet> {

            private ArrayList<Tweet> tweets;

            public TweetListAdaptor(Context context,

                                                                       int textViewResourceId,
                                                                       ArrayList<Tweet> items) {
                      super(context, textViewResourceId, items);
                      this.tweets = items;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                    View v = convertView;
                    if (v == null) {
                            LayoutInflater vi = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                            v = vi.inflate(R.layout.list_item, null);
                    }
                    Tweet o = tweets.get(position);

                    TextView tt = (TextView) v.findViewById(R.id.toptext);
                    TextView bt = (TextView) v.findViewById(R.id.bottomtext);
                    tt.setText(o.content);
                    bt.setText(o.author);
                    return v;
            }
       }
}

Tweet.java Tweet.java

public class Tweet {
    String author;
    String content;
}

Problem might be in this code 问题可能在此代码中

  HttpGet("http://search.twitter.com/search.json?q=android");

You are using wrong URL..... 您使用的URL错误.....

"The Twitter REST API v1 is no longer active..."

You have to use REST API v1.1. 您必须使用REST API v1.1。 for fetching twitter data... 用于获取Twitter数据...

for that you have to follow below URL... 为此,您必须遵循以下URL ...

"https://api.twitter.com/1.1/search/tweets.json?q=android"

DOCUMENTATION 文档

Note : You have to pass CONSUMER_KEY & CONSUMER_SECRET to get data to the URL... 注意:您必须传递CONSUMER_KEYCONSUMER_SECRET才能将数据获取到URL ...

Follow this "TWITTER CONSOLE" ..it will help you to give you desired output with its console...if successful then implement it on your program.. 遵循此“ TWITTER CONSOLE” ..它将帮助您通过其控制台提供所需的输出...如果成功,则在程序上实现它。

I have fetched TWIITER TWEETS...This code could be useful to you.......... 我已经拿到了TWIITER TWEETS ...此代码可能对您有用..........

CODE : 代码:

private class DownloadTwitterTask extends AsyncTask<String, Void, String> {
        final static String CONSUMER_KEY = "***************";
        final static String CONSUMER_SECRET = "******************";

        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=";
        ProgressDialog pDialog;

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            pDialog = new ProgressDialog(SearchList.this);
            pDialog.setMessage("Loading Tweets....");
            pDialog.show();
            super.onPreExecute();
        }

        @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) {

        // converts a string of JSON data into a list objects
            listItems = new ArrayList<ListModel>();
            if (result != null && result.length() > 0) {
                try{
                    JSONArray sessions = new JSONArray(result);
                    Log.i("Result Array", "Result : "+result);
                    for (int i = 0; i < sessions.length(); i++) {
                            JSONObject session = sessions.getJSONObject(i);
                                ListModel lsm = new ListModel();
                                lsm.setTxt_content(session.getString("text"));

                                String dte = session.getString("created_at");
                                SimpleDateFormat dtformat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzzz yyyy");
                                Date d = dtformat.parse(dte);
                                SimpleDateFormat dtfm = new SimpleDateFormat("EEE, MMM dd, hh:mm:ss a yyyy");
                                String date = dtfm.format(d);

                                lsm.setTxt_date(date);
                                listItems.add(lsm);

                    }
                        if (listItems.size() <= 0 ) {
                            Toast.makeText(getApplicationContext(), "No Tweets From User : "+ScreenName, Toast.LENGTH_SHORT);
                        }

                    }
                catch (Exception e){
                    Log.e("Tweet", "Error retrieving JSON stream" + e.getMessage());
                    Toast.makeText(getApplicationContext(), "Couldn'f Found User :"+ScreenName, Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            }

            // send the values to the adapter for rendering
            //ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), R.layout.tweet_main, listItems);
            cust = new CustomAdapter(activity, listItems);
            list.setAdapter(cust);
            pDialog.dismiss();
        }

        // convert a JSON authentication object into an Authenticated object
        private Authenticated jsonToAuthenticated(String rawAuthorization) {
            Authenticated auth = new Authenticated();
            if (rawAuthorization != null && rawAuthorization.length() > 0) {

                try{
                            JSONObject session = new JSONObject(rawAuthorization);
                            auth.access_token= session.getString("access_token");
                            auth.token_type= session.getString("token_type");
                    }
                catch (Exception e){
                    Log.e("jsonToAuthenticated", "Error retrieving JSON Authenticated Values : " + e.getMessage());
                    e.printStackTrace();
                }
            }
            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 username) {
            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);
                Log.i("getTwitterStream", "rawAuthoruzation : "+rawAuthorization);
                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 + username);

                    // 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) {
                Log.i("UnsupportedEncodingException", ex.toString());
            } catch (IllegalStateException ex1) {
                Toast.makeText(getApplicationContext(), "Couldn't find specified user : ", Toast.LENGTH_SHORT).show();
                Log.i("IllegalStateException", ex1.toString());
            }
            return results;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM