【问题标题】:Twitter4j , searching for tweets with keywordTwitter4j ,搜索带有关键字的推文
【发布时间】:2015-02-04 20:27:33
【问题描述】:

我正在做一个推特项目,用特定关键字搜索所有公共推文。 以下使我的应用崩溃:

 private void searchTweets() {

        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true)
                .setOAuthConsumerKey(getString(R.string.twitter_consumer_key))
                .setOAuthConsumerSecret(getString(R.string.twitter_consumer_secret))
                .setOAuthAccessToken(getString(R.string.twitter_access_token))
                .setOAuthAccessTokenSecret(getString(R.string.twitter_token_secret));

        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();


        try {
            Query query = new Query("India");
            QueryResult result;
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                   // System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
                    Log.e("TweetSearch",tweet.getUser().getScreenName() + " - " + tweet.getText() ) ;

                }
            } while ((query = result.nextQuery()) != null);
            System.exit(0);
        } catch (TwitterException te) {
            te.printStackTrace();
           // System.out.println("Failed to search tweets: " + te.getMessage());

            Log.e("TweetSearch", te.getMessage());
            System.exit(-1);
        }
    }

我想在列表中显示推文。我已经处理了所有所需的身份验证,并且应用程序身份验证流程没问题。如何知道搜索到的推文的 JSON 数据,以便将其解析到我的列表中?

我试过了,如何实现异步任务?

public class LimetrayTweets extends Activity {

    public static final String TAG = "TweetSearch";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_limetray_tweets);

        SearchTweet("Limetray");



    }

    public static String SearchTweet(String searchTerm) {
        HttpURLConnection httpConnection = null;
        BufferedReader bufferedReader = null;
        StringBuilder response = new StringBuilder();

        try {



            URL url = new URL(Constants.URL_SEARCH +  URLEncoder.encode("#" + searchTerm) + "&result_type=mixed&lang=en");
            Log.e(TAG, "url twitter search: " + url.toString());

            httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setRequestMethod("GET");


            String jsonString = appAuthentication();
            JSONObject jsonObjectDocument = new JSONObject(jsonString);
            String token = jsonObjectDocument.getString("token_type") + " " +
                    jsonObjectDocument.getString("access_token");

            httpConnection.setRequestProperty("Authorization", token);
            httpConnection.setRequestProperty("Content-Type", "application/json");
            httpConnection.connect();

            bufferedReader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));

            String line;
            while ((line = bufferedReader.readLine()) != null){
                response.append(line);
            }

            Log.d(TAG, "GET response code: " + String.valueOf(httpConnection.getResponseCode()));
            Log.d(TAG, "JSON response: " + response.toString());


        } catch (Exception e) {
            Log.e(TAG, "GET error: " + Log.getStackTraceString(e));

        }finally {
            if(httpConnection != null){
                httpConnection.disconnect();

            }
        }

        return response.toString();
    }

    public static String appAuthentication(){

        HttpURLConnection httpConnection = null;
        OutputStream outputStream = null;
        BufferedReader bufferedReader = null;
        StringBuilder response = null;

        try {
            URL url = new URL(Constants.URL_AUTHENTICATION);
            httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setRequestMethod("POST");
            httpConnection.setDoOutput(true);
            httpConnection.setDoInput(true);

            String accessCredential = Constants.CONSUMER_KEY + ":" + Constants.CONSUMER_SECRET;
            String authorization = "Basic " + Base64.encodeToString(accessCredential.getBytes(), Base64.NO_WRAP);
            String param = "grant_type=client_credentials";

            httpConnection.addRequestProperty("Authorization", authorization);
            httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            httpConnection.connect();

            outputStream = httpConnection.getOutputStream();
            outputStream.write(param.getBytes());
            outputStream.flush();
            outputStream.close();
//            int statusCode = httpConnection.getResponseCode();
//            String reason =httpConnection.getResponseMessage();

            bufferedReader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
            String line;
            response = new StringBuilder();

            while ((line = bufferedReader.readLine()) != null){
                response.append(line);
            }

            Log.d(TAG, "POST response code: " + String.valueOf(httpConnection.getResponseCode()));
            Log.d(TAG, "JSON response: " + response.toString());

        } catch (Exception e) {
            Log.e(TAG, "POST error: " + Log.getStackTraceString(e));

        }finally{
            if (httpConnection != null) {
                httpConnection.disconnect();
            }
        }
        return response.toString();
    }

【问题讨论】:

  • uff...老兄。你有什么累的?我给了你我的工作代码。你不知道如何实现它?看不到你的方法确实返回查询结果的响应。你把它存储在哪里? 1st学习如何实现Listview。请..我要删除我的答案..够了。你甚至不知道方法返回的东西?Stackoverflow 不是你的导师..
  • 我非常感谢您的 cmets。在刷新我的概念后,我将重新开始这个项目。非常感谢

标签: android twitter twitter4j


【解决方案1】:

我正在为你发布我的实时代码。希望它对你有用。 SearchTerm 是您搜索的关键字。下面的方法将返回一个字符串中的 json 响应。

如果你想要 gson 序列化类。我会为你提供的

ProgressDialog pd;

            new DownloadTwitterTask().execute(keyword);

 private class DownloadTwitterTask extends AsyncTask<String, Void, String> {
            @Override
            protected void onPreExecute() {
                // TODO Auto-generated method stub
                super.onPreExecute();
                pd = ProgressDialog.show(Mainactivity.this, "",
             "Loading.....", true, false);

            }

        protected String doInBackground(String... searchTerms) {
                    String result = null;

                    if (searchTerms.length > 0) {

                        result = TwitterUtils.getTimelineForSearchTerm(searchTerms[0]);

                    }
                    return result;
                }
    @Override
            protected void onPostExecute(String result) {
    if (pd != null && pd.isShowing()) {
        pd.dismiss();
    }
                Log.e("twitter Result ", result);

       //Result contains json response. take a arraylist of objects and pass //arralist  to adpater of listview. 

    }

}

getTimelineForSearchTerm 方法:

public static String getTimelineForSearchTerm(String searchTerm){
          HttpURLConnection httpConnection = null;
          BufferedReader bufferedReader = null;
          StringBuilder response = new StringBuilder();

          try {



              URL url = new URL(ConstantsUtils.URL_SEARCH +  URLEncoder.encode("#"+searchTerm) + "&result_type=mixed&lang=en");
              Log.e(TAG, "url twitter search: " + url.toString());

              httpConnection = (HttpURLConnection) url.openConnection();
              httpConnection.setRequestMethod("GET");


              String jsonString = appAuthentication();
              JSONObject jsonObjectDocument = new JSONObject(jsonString);
              String token = jsonObjectDocument.getString("token_type") + " " +
                      jsonObjectDocument.getString("access_token");

              httpConnection.setRequestProperty("Authorization", token);
              httpConnection.setRequestProperty("Content-Type", "application/json");
              httpConnection.connect();

              bufferedReader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));

              String line;
              while ((line = bufferedReader.readLine()) != null){
                  response.append(line);
              }

              Log.d(TAG, "GET response code: " + String.valueOf(httpConnection.getResponseCode()));
              Log.d(TAG, "JSON response: " + response.toString());


        } catch (Exception e) {
            Log.e(TAG, "GET error: " + Log.getStackTraceString(e));

        }finally {
            if(httpConnection != null){
                httpConnection.disconnect();

            }
        }

        return response.toString();
    }   
}

app认证方法:

public static final String TAG = "TwitterUtils";

    public static String appAuthentication(){

        HttpURLConnection httpConnection = null;
        OutputStream outputStream = null;
        BufferedReader bufferedReader = null;
        StringBuilder response = null;

        try {
            URL url = new URL(ConstantsUtils.URL_AUTHENTICATION);
            httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setRequestMethod("POST");
            httpConnection.setDoOutput(true);
            httpConnection.setDoInput(true);

            String accessCredential = ConstantsUtils.CONSUMER_KEY + ":" + ConstantsUtils.CONSUMER_SECRET;
            String authorization = "Basic " + Base64.encodeToString(accessCredential.getBytes(), Base64.NO_WRAP);
            String param = "grant_type=client_credentials";

            httpConnection.addRequestProperty("Authorization", authorization);
            httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            httpConnection.connect();

            outputStream = httpConnection.getOutputStream();
            outputStream.write(param.getBytes());
            outputStream.flush();
            outputStream.close();
//            int statusCode = httpConnection.getResponseCode();
//            String reason =httpConnection.getResponseMessage();

            bufferedReader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
            String line;
            response = new StringBuilder();

            while ((line = bufferedReader.readLine()) != null){
                response.append(line);
            }

            Log.d(TAG, "POST response code: " + String.valueOf(httpConnection.getResponseCode()));
            Log.d(TAG, "JSON response: " + response.toString());

        } catch (Exception e) {
            Log.e(TAG, "POST error: " + Log.getStackTraceString(e));

        }finally{
            if (httpConnection != null) {
                httpConnection.disconnect();
            }
        }
        return response.toString();
    }

实用程序:

public class ConstantsUtils {

    public static final String URL_ROOT_TWITTER_API = "https://api.twitter.com";
    public static final String URL_SEARCH = URL_ROOT_TWITTER_API + "/1.1/search/tweets.json?q=";
    public static final String URL_AUTHENTICATION = URL_ROOT_TWITTER_API + "/oauth2/token";
    public static final String CONSUMER_KEY = "";
    public static final String CONSUMER_SECRET = "";
}

【讨论】:

  • 感谢您的快速回复,您是否正在使用任何额外的库或只是 twitter4j?
  • 我使用 Twitter Rest api 进行搜索。 Twitter4j 仅用于发布新推文。!我的代码不需要 twitter4j ..请尝试。你会得到回应。从 asyntask 调用 getTimelineForSearchTerm
  • 试代码,想看看GSON序列化。
  • 如果你得到回复,请告诉我。我肯定会发布它。没有回复它有什么用。
【解决方案2】:

Twitter4j 成功实施:

@Override
protected ArrayList<String> doInBackground(String... arg0) {

    List<twitter4j.Status> tweets = new ArrayList();
    tweetTexts.clear();

    Twitter mTwitter = getTwitter();
    try {

        tweets = mTwitter.search(new Query(searchText)).getTweets();
        for (twitter4j.Status t : tweets) {
        tweetTexts.add(t.getText() + "\n\n");
        }

    } catch (Exception e) {
        Log.e("Error", "Exception");
    }



    return tweetTexts;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    • 2014-07-10
    • 2018-09-12
    • 1970-01-01
    相关资源
    最近更新 更多