0
這是我第一次使用Twitter API。我正在編寫一個基本的應用程序,當用戶鍵入一個短語時,它會返回最後15個短語的短語。如果他們鍵入用戶名並單擊「搜索用戶」按鈕,它將返回來自該用戶的最後15個推文。使用Twitter API訪問Twitter流 - 使用Java
我相信我已經完成了第一部分,但有點困擾搞清楚如何從特定用戶提出推文。任何進一步的指導最受讚賞。
package twitter;
import java.awt.Button;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.List;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.TwitterStream;
public class SearchListener extends KeyAdapter implements ActionListener {
private Button searchButton;
private Button searchUserButton;
private TextField searchText;
private TextArea results;
private Twitter twitter;
public SearchListener(Button searchButton, Button searchUserButton,
TextField searchText, TextArea results) {
this.searchButton = searchButton;
this.searchUserButton = searchUserButton;
this.searchText = searchText;
this.results = results;
results.setText("(ready for search)");
twitter = (new TwitterFactory()).getInstance();
}
@Override
public void actionPerformed(ActionEvent e) {
doSearch();
}
private void doSearch() {
String searchStr = searchText.getText();
results.setText("searching for: " + searchStr + "\n");
if (searchStr == null || searchStr.length() == 0) {
return;
}
try {
QueryResult result = twitter.search(new Query(searchStr));
List<Tweet> tweets = result.getTweets();
int i = 0;
for (Tweet tweet : tweets) {
results.append("" + i + ": ");
results.append("@" + tweet.getFromUser() + " - "
+ tweet.getText());
results.append("\n\n");
i++;
}
results.append("" + i + " total tweets found\n");
} catch (TwitterException te) {
te.printStackTrace();
results.append("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}
}
@Override
public void keyTyped(KeyEvent e) {
// results.append(e.getKeyChar() + "\n");
if (e.getKeyChar() == '\n') {
doSearch();
}
}
}