Programming the Google Web API with Java

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 [Section 5.4], programming to the Google API in Java couldn’t be simpler. The googleapi.jar archive includes com.google.soap.search, a nice clean wrapper around the underlying Google SOAP, along with the Apache Software Foundation’s open source Crimson (http://xml.apache.org/crimson) XML parser and Apache SOAP (http://xml.apache.org/soap/) stack, among others.

Tip

You’ll need a copy of the Java 2 Platform, Standard Edition (J2SE, http://java.sun.com/downloads/) to compile and run this hack.

The Code

// Googly.java // Bring in the Google SOAP wrapper import com.google.soap.search.*; import java.io.*; 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>"); System.exit(1); } // Create a new GoogleSearch object GoogleSearch s = new GoogleSearch( ); try { s.setKey(googleKey); s.setQueryString(args[0]); // Google query from the command-line s.setMaxResults(10); // Query Google GoogleSearchResult r = s.doSearch( ); // Gather the results GoogleSearchResultElement[] re = r.getResultElements( ...

Get Google Hacks now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.