【问题标题】:Fetching tweets from twitter using JSON in API v1.1在 API v1.1 中使用 JSON 从 Twitter 获取推文
【发布时间】:2014-09-19 16:09:58
【问题描述】:

Twitter REST API v1 不再处于活动状态。我需要进行哪些修改才能在 API v1.1 中运行此代码。这是我从用于 API v1 的特定 uri 从 twitter 获取推文的代码 -

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");

【问题讨论】:

    标签: android json twitter


    【解决方案1】:

    你使用了错误的网址.....

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

    您必须使用 REST API v1.1. 来获取 twitter 数据...

    为此,您必须遵循以下网址...

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

    DOCUMENTATION

    注意:您必须传递 CONSUMER_KEYCONSUMER_SECRET 才能将数据获取到 URL...

    关注这个"TWITTER CONSOLE"..它将帮助您通过其控制台为您提供所需的输出...如果成功,然后在您的程序中实现它..

    我已获取 TWIITER 推文...此代码可能对您有用..........

    代码:

    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;
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2013-08-19
      • 1970-01-01
      • 1970-01-01
      • 2013-09-08
      • 2013-12-04
      • 2013-05-30
      • 2013-06-09
      • 2015-11-15
      • 2016-06-21
      相关资源
      最近更新 更多