在API v1.1中使用JSON从twitter获取tweet



Twitter REST API v1不再激活。我需要做什么修改才能在API v1.1中运行此代码。这是我的代码从twitter从特定的uri这是用于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

public class Tweet {
    String author;
    String content;
}

问题可能在此代码

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

您使用了错误的URL.....

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

必须使用REST API v1.1。用于获取twitter数据…

你必须遵循下面的URL…

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

注意:必须通过CONSUMER_KEY &CONSUMER_SECRET获取数据到URL…

关注这个"TWITTER控制台"..它将帮助你给你想要的输出与它的控制台…如果成功,那么在你的程序中实现它。

我已经获取了twitter 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;
        }
    }

最新更新