Program Google in Java

Programming the Google Web API in Java is a snap, thanks to 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, programming 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

In addition to the googleapi.jar file included in the Google API Developer’s Kit, 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

Save the following code to a file called Googly.java:

// 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 ...

Get Google Hacks, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.