I'm trying to get the hits of a google search from a string of the query.
public class Utils {
public static int googleHits(String query) throws IOException {
String googleAjax = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
String json = stringOfUrl(googleAjax + query);
JsonObject hits = new Gson().fromJson(json, JsonObject.class);
return hits.get("estimatedResultCount").getAsInt();
}
public static String stringOfUrl(String addr) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
URL url = new URL(addr);
IOUtils.copy(url.openStream(), output);
return output.toString();
}
public static void main(String[] args) throws URISyntaxException, IOException {
System.out.println(googleHits("odp"));
}
}
The following exception is thrown:
Exception in thread "main" java.lang.NullPointerException
at odp.compling.Utils.googleHits(Utils.java:48)
at odp.compling.Utils.main(Utils.java:59)
What am I doing incorrectly? Should I be defining an entire object for the Json return? That seems excessive, given that all I want to do is get one value.
For reference: the returned JSON structure.