Friday, May 20, 2011

Dev: How to search google images in java

I'm finishing up the final touches of the next version which will include album art.  One of the features I included was a built in google image search to look for album art.  It was extremely simple to set up so I'd like to share some of the code.  I decided to use JSON as a return type for my queries and there are some simple free classes out there to parse the results here http://json.org/java/

The google image api documentation shows us how to do a simple query, so lets construct one.

String search_string = "nachos";
String query = "https://ajax.googleapis.com/ajax/services/earch/images?v=1.0&q=" + search_string;

Now do a http GET

HttpClient client = new DefaultHttpClient();  
try
{   
   HttpGet request = new HttpGet(query);
          
   HttpResponse http_response = client.execute(request);
   HttpEntity entity = http_response.getEntity();

   if (entity != null)
   {
      InputStream instream = entity.getContent();
      //convertInputStreamToString does exactly what it says.. its trivial so no need to show the code
      String response = convertInputStreamToString(instream);
      //JSONObject is provided at the link above
      JSONObject json = new JSONObject(response);
      parseJson(json);
                              
      instream.close();
   }
}
catch (Exception ex)
{
    client.getConnectionManager().shutdown();
}       


The parseJson function is where you can get the relevant data out of the results.  The list of valid keys are listed in the api documentation I linked above.  Here is the code for parseJson:

JSONObject response_data = JsonObj.getJSONObject("responseData");
JSONArray results = response_data.getJSONArray("results");

for (int i = 0; i < results.length(); i++)
{
    JSONObject result = (JSONObject)results.get(i);
    //now you can grab data from the result using:
    //result.getInt(key);
    //result.getString(key);
    //etc
}

Now you have access to google image search.  The other google apis work pretty much the same way from what I've seen.