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 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
in place of insert keyhere, like so:
// Your Google API developer's key.
private static String googleKey = "12BuCK13mY5h0E/34KN0cK@ttH3Do0R
";