I'm writing a java web application to retrieve tweets by using Twitter API. I got a Search method and trying to call the method at 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 the String to JSON object, but it shows HTTP 500 NullPointerException error I don't know where i'm getting wrong because i'm new to JAVA. Could anybody help? Really appreciate!