I am writing a java web application to extract tweets using the Twitter API. I got the search method and tried to call the method on the jsp page.
public class SearchTwitter {
private static final String CONSUMER_KEY = "*************";
private static final String CONSUMER_SECRET = "****************";
private static final String OAUTH_TOKEN = "*********************";
private static final String OAUTH_TOKEN_SECRET = "*****************";
public String Search(String query) throws Exception {
OAuthConsumer consumer = new DefaultOAuthConsumer(CONSUMER_KEY,
CONSUMER_SECRET);
consumer.setTokenWithSecret(OAUTH_TOKEN, OAUTH_TOKEN_SECRET);
query = query.replaceAll(" ", "%20");
String twitterURL = "https://api.twitter.com/1.1/search/tweets.json?q=" + query + "&src=typd";
URL url = new URL(twitterURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.setDoOutput(true);
request.setRequestProperty("Content-Type", "application/json");
request.setRequestProperty("Accept", "application/json");
request.setRequestMethod("GET");
consumer.sign(request);
request.connect();
StringBuilder text = new StringBuilder();
InputStreamReader in = new InputStreamReader((InputStream) request.getContent());
BufferedReader buff = new BufferedReader(in);
System.out.println("Getting data ...");
String line;
do {
line = buff.readLine();
text.append(line);
} while (line != null);
String strResponse = text.toString();
return strResponse;
}
}
The search method returns a string.
<%
SearchTwitter stw = new SearchTwitter();
String tweet = request.getParameter("query");
JSONObject result = new JSONObject(stw.Search(tweet));
JSONArray statuses = result.getJSONArray("statuses");
for (int i = 0; i < statuses.length(); i++) {
String time = statuses.getJSONObject(i).getString("created_at");
String user = statuses.getJSONObject(i).getJSONObject("user").getString("screen_name");
String text = statuses.getJSONObject(i).getString("text");
System.out.println(time.toString());
System.out.println(user.toString());
System.out.println(text.toString());
}
%>
And I'm trying to convert a String object to JSON, but it shows an HTTP 500 error NullPointerException I donβt know where I am mistaken because I am new to JAVA. Can anyone help? I really appreciate it!
source
share