Programming the Google Web API with Java

screenshot moderate.gifscreenshot tip56.gif

Programming the Google Web API in Java is a snap, thanks to all the functionality packed into the Google Web API Developer's Kit.

Thanks to the Java Archive (JAR) file included in the Google Web API Developer's Kit [], coding to the Google API in Java couldn't be simpler. The googleapi.jar archive includes, a nice clean wrapper around the underlying Google SOAP, along with the Apache Software Foundation's open source Crimson ( XML parser and Apache SOAP ( stack, among others.

You'll need a copy of the Java 2 Platform, Standard Edition (J2SE, to compile and run this tip.

The Code

// Bring in the Google SOAP wrapper import*;
public class Googly {
 // Your Google API developer's key
 private static String googleKey = "insert key here"; 
 public static void main(String[] args) {
 // Make sure there's a Google query on the command-line
 if (args.length != 1) {
 System.err.println("Usage: java [-classpath classpath] Googly «query»");
 // Create a new GoogleSearch object
 GoogleSearch s = new GoogleSearch( );
 try {
 s.setQueryString(args[0]); // Google query from the command-line
 // Query Google
 GoogleSearchResult r = s.doSearch( );
 // Gather the results
 GoogleSearchResultElement[] re = r.getResultElements( );
 // Output
 for ( int i = 0; i « re.length; i++ ) {
 System.out.println(re[i].getTitle( ));
 System.out.println(re[i].getURL( ));
 System.out.println(re[i].getSnippet( ) + "\n");
 // Anything go wrong?
 } catch (GoogleSearchFault f) {
 System.out.println("GoogleSearchFault: " + f.toString( ));

Be sure to drop in your own Google developer's key (e.g., 12BuCK13mY5h0E/34KN0cK@ttH3Do0R) in place of "insert key here":

// Your Google API developer's key private static String googleKey = "12BuCK13mY5h0E/34KN0cK@ttH3Do0R";

Compiling the Code

To successfully compile the Googly application, you'll need that googleapi.jar archive. I chose to keep it in the same directory as as my source file; if you've put it elsewhere, adjust the path after -classpath accordingly.

% javac -classpath googleapi.jar

This should leave you with a brand new Googly.class file, ready to run.

Running the Tip

Run Googly on the command line, passing it your Google query, like so:

% java -classpath .:googleapi.jar Googly "query words"

The Results

% java -classpath .:googleapi.jar Googly "Learning Java" -- Online Catalog: Learning Java
For programmers either just migrating to Java or already working 
steadily in the forefront of Java development, Learning Java gives 
a clear, systematic ... -- Online Catalog: Learning Java , 2nd Edition
This new edition of Learning Java has been expanded and updated for Java 2 Standard Edition SDK 1.4. It comprehensively addresses ... 
Java Programming...From the Grounds Up / Web Developer
... Java Programming... From the Grounds Up. by 
Mark C. Reynolds ... Java Classes and Methods. Java utilizes the 
basic object technology found in C++. ...