Zamples, Inc. logo
 Home   Search   Solutions   My Zamples   FAQ   News   Contact 
Zamples ID:
Password:
   
0 anonymous users;
16 users logged in.

Live Samples
Live APIs

HTML or JSP Frag
Java Servlet Frag
HTML & Applet
Bash
C# (Mono)
C++ (gcc)
Groovy
Haskell (Hugs98)
J2SE 1.4 Class
J2SE 1.4 Fragment
J2SE 5.0 Class
J2SE 5.0 Fragment
J2SE 6.0 Class
J2SE 6.0 Fragment
Perl
Python
Ruby
 
Google Search API Code Examples

Google has a very nice Web Services API.  These examples illustrate that a programmer using this API never is hardly aware that Web Services is involved.  We have integrated the Google developer's kit into this Zamples installation, so you don't need to download or install it.

You can also view the Javadocs for the Google Web Services API.

Simple Search

Here is a code fragment for a simple search.  We have pasted in our Google key for you.  Try modifying the search string and rerunning the search:

GoogleSearch s = new GoogleSearch();
s.setKey("H/ufNfpQFHIXOhEAuGHVIRl59K66koWo");
s.setQueryString("happiness");
try {
    GoogleSearchResult r = s.doSearch();
    out.println("<h2>Google Search Results</h2>");
    out.println(r.toString());
} catch (Exception f) {
    out.println("The call to the Google Web API failed:");
    out.println(f.toString());
}

Typical Output (Google limits the response to 10 results)

These results aren't documented anywhere that the author could find, but it is apparent that the first attribute returned (TM) is the time spent for the search, and the second attribute (Q) is the search string.  The examples that follow perform futher manipulation of the results.  The results have been folded so they would not be too wide when displayed.

Google Search Results

{
TM = 0.139481
Q = "happiness"
CT = ""
TT = ""
CATs =
{
{SE="", FVN="Top/Games/Board_Games/Titles/H/Happiness"}
}
Start Index = 1
End Index = 10
Estimated Total Results Number = 1100000
Document Filtering = true
Estimate Correct = false
Rs =
{

[
URL = "http://www.happiness.com/"
Title = "Happiness.com"
Snippet = " ... printed edition. Happiness tips, games, gifts, etc. ... Spreading Happiness for Over 35 Years". Visit us weekly--New content every Sunday. ... "
Directory Category = {SE="", FVN=""}
Directory Title = ""
Summary = ""
Cached Size = "18k"
Related information present = true
Host Name = ""
],

[
URL = "http://www.thewaytohappiness.org/"
Title = "The Way to Happiness"
Snippet = "The Way to Happiness book is a guide to successful and happy living, teaches in a way that makes sense and enables you to make intelligent decisions in life ... "
Directory Category = {SE="", FVN="Top/Society/Religion_and_Spirituality/Scientology/Church_of_Scientology/Ethics_and_Morals"}
Directory Title = "The Way to Happiness International"
Summary = "A nonprofit organization whose purpose is to disseminate the book "The Way to Happiness." Suggestions..."
Cached Size = "40k"
Related information present = true
Host Name = ""
],

[
URL = "http://www.amazon.com/exec/obidos/tg/detail/-/1573221112?v=glance"
Title = "Amazon.com: Books: The Art of Happiness: A Handbook for Living"
Snippet = " ... These are the conundrums that psychiatrist Howard Cutler poses to the Dalai Lama during an extended period of interviews in The Art of Happiness: A Handbook ... "
Directory Category = {SE="", FVN=""}
Directory Title = ""
Summary = ""
Cached Size = "73k"
Related information present = true
Host Name = ""
],

[
URL = "http://www.amazon.com/exec/obidos/tg/detail/-/B00000IC7G?v=glance"
Title = "Amazon.com: DVD: Happiness (1998)"
Snippet = "Happiness, Todd Solondz, Jane Adams (II), Jon Lovitz, Philip Seymour Hoffman, Dylan Baker, Lara Flynn Boyle, Justin Elvin, Cynthia Stevenson, Lila Glantzman ... "
Directory Category = {SE="", FVN=""}
Directory Title = ""
Summary = ""
Cached Size = "65k"
Related information present = true
Host Name = "www.amazon.com"
],

[
URL = "http://www.healthhappiness.com.au/"
Title = "Welcome to Health & Happiness For You"
Snippet = "Health and Happiness for You, view items in shopping cart, ... Welcome to Health & Happiness For You where we promote the 'experience' of life. PRODUCT OF THE MONTH. ... "
Directory Category = {SE="", FVN="Top/Health/Alternative/Holistic_and_Integrated_Medicine"}
Directory Title = "Health and Happiness For You"
Summary = "A journey of self improvement giving answers to those searching for better lives in a simple plan..."
Cached Size = "28k"
Related information present = true
Host Name = ""
],

[
URL = "http://www.happiness.co.uk/"
Title = "Welcome to The Happiness Project"
Snippet = "Quote of the Moment. "There is a world of difference between searching for happiness and choosing to be happy.". Robert Holden Happiness is a Way of Travelling. ... "
Directory Category = {SE="", FVN="Top/Health/Mental_Health/Self-Help"}
Directory Title = "Happiness Project"
Summary = "Designers of the healing and personal development program behind the BBC documentary 'How to be Happy'...."
Cached Size = "21k"
Related information present = true
Host Name = ""
],

[
URL = "http://www.happiness-is-online.com/"
Title = "Happiness Is - Empower your life with the largest collection of ... "
Snippet = "Famous quotations: beat the blues with the largest collection of inspirational and motivational quotes about happiness on the web. ... HAPPINESS QUOTES. ... "
Directory Category = {SE="", FVN="Top/Reference/Quotations/Inspirational"}
Directory Title = "Happiness Is"
Summary = "Collection of inspirational and motivational quotes, arranged alphabetically."
Cached Size = "59k"
Related information present = true
Host Name = ""
],

[
URL = "http://www.eur.nl/fsw/research/happiness/"
Title = "World Database of Happiness"
Snippet = ""
Directory Category = {SE="", FVN="Top/Science/Social_Sciences/Psychology/Personality"}
Directory Title = "World Database of Happiness"
Summary = "A continuous register of scientific research on subjective appreciation of life directed by Ruut Veenhove..."
Cached Size = "1k"
Related information present = true
Host Name = ""
],

[
URL = "http://www.authentichappiness.org/"
Title = "Authentic Happiness - Using the New Positive Psychology"
Snippet = "Authentic Happiness: Using the New Positive Psychology to Realize Your Potential for Lasting Fulfillment. ... PANAS Questionnaire. General Happiness Scale. ... "
Directory Category = {SE="", FVN=""}
Directory Title = ""
Summary = ""
Cached Size = "28k"
Related information present = true
Host Name = ""
],

[
URL = "http://www.un-official.com/The_Daily_Script/happiness.txt"
Title = "<html> <head> </head><body><pre>&lt;html&gt; &lt;head&gt; &lt;/ ... "
Snippet = "<html> <head> </head><body><pre>&lt;html&gt; &lt;head&gt; &lt;/head&gt;&lt;body&gt;&lt;pre&gt; HAPPINESS Written and Directed by Todd Solondz 1. EXT. ... "
Directory Category = {SE="", FVN="Top/Arts/Movies/Titles/H/Happiness"}
Directory Title = "Un-Official: Happiness"
Summary = "Screenplay for the film by Todd Solondz."
Cached Size = "101k"
Related information present = true
Host Name = ""
]
}
}

Simple Search with SafeSearch Enabled

Google's SafeSearch is enabled by default when you use google.com to do a search.  You can easily turn it on for a Google Web Services API call:

GoogleSearch s = new GoogleSearch();
s.setKey("H/ufNfpQFHIXOhEAuGHVIRl59K66koWo");
s.setQueryString("happiness");
s.setSafeSearch(true);
try {
    GoogleSearchResult r = s.doSearch();
    out.println("<h2>Google Search Results</h2>");
    out.println(r.toString());
} catch (Exception f) {
    out.println("The call to the Google Web API failed:");
    out.println(f.toString());
}

Spelling Suggestion

Google can offer alternative spellings for search terms.  The call returns null if there are no alternative terms:

GoogleSearch s = new GoogleSearch();
s.setKey("H/ufNfpQFHIXOhEAuGHVIRl59K66koWo");
try {
    out.println("<h2>Google Spelling Suggestion</h2>");
    out.println(s.doSpellingSuggestion("gooogle"));
} catch (Exception f) {
    out.println("The call to the Google Web Service API failed:");
    out.println(f.toString());
}

Result

google

Search Directory Category

GoogleSearch s = new GoogleSearch();
s.setKey("H/ufNfpQFHIXOhEAuGHVIRl59K66koWo");
s.setQueryString("joy");
try {
    GoogleSearchResult r = s.doSearch();
    out.println("<h2>Google Search Result Categories</h2>");
    GoogleSearchDirectoryCategory[] dcs = r.getDirectoryCategories();
    for (int i=0; i<dcs.length; i++)
       out.println(dcs[i].getFullViewableName());
} catch (Exception f) {
    out.println("The call to the Google Web Service API failed:");
    out.println(f.toString());
}

Results

Top/Arts/Music/Styles/Rock/Gothic/Bands_and_Artists/J/Joy_Division

Result Count

You can determine the total number of results returned, as well as an indication of whether this is an exact or an approximate figure.

GoogleSearch s = new GoogleSearch();
s.setKey("H/ufNfpQFHIXOhEAuGHVIRl59K66koWo");
s.setQueryString("love");
try {
    GoogleSearchResult r = s.doSearch();
    out.println("<h2>Google Search Result Count</h2>");
    out.print(r.getEstimateIsExact() ? "Exactly " : "Approximately ");
    out.println(r.getEstimatedTotalResultsCount() + " results were found");
} catch (Exception f) {
    out.println("The call to the Google Web Service API failed:");
    out.println(f.toString());
}

Results

Approximately 1030 results were found

Sorted result counts

Here is a variation on the previous example.

String[] arrayDomainNames = {
		"www.supremeind.com",
		"www.surewest.com",
		"www.somersetvalleybank.com",
		"www.zoran.com",
		"www.zumiez.com",
		"www.zygo.com"
	};

GoogleSearch s = new GoogleSearch();
s.setKey("lJ9aQ0hQFHJmUeehw9ISh5ZsUYGWOguN");
TreeMap sortedHash = new TreeMap();
int i = 0;
try {
    for (i=0; i<arrayDomainNames.length; i++) {
        s.setQueryString(arrayDomainNames[i]);
        GoogleSearchResult r = s.doSearch();
        String domainInfo = arrayDomainNames[i] + " " + (r.getEstimateIsExact() ?"(exact)" :"(approximate)");
        sortedHash.put(new Integer(r.getEstimatedTotalResultsCount()), domainInfo);
    }
    Iterator iterator = sortedHash.keySet().iterator();
    System.out.println("<h2>Sorted Google Search Result Count</h2>");
    while (iterator.hasNext()) {
    	Integer key = (Integer)iterator.next();
    	System.out.println(key + " " + sortedHash.get(key));
    }
} catch (GoogleSearchFault gsf) {
     System.out.println("Error processing item #" + (i-1) + " + arrayDomainNames[i]; " + gsf);
}

Results

This example takes a while to run, and sometimes Google coughs up an error message.  If that happens, just try running the example again.

Sorted Google Search Result Count

176 www.somersetvalleybank.com (approximate) 664 www.supremeind.com (approximate) 11900 www.zygo.com (approximate) 16500 www.zumiez.com (approximate) 19600 www.zoran.com (approximate) 52600 www.surewest.com (approximate)

Search Time

You can easily discover how many seconds a search took:

GoogleSearch s = new GoogleSearch();
s.setKey("H/ufNfpQFHIXOhEAuGHVIRl59K66koWo");
s.setQueryString("love");
try {
    GoogleSearchResult r = s.doSearch();
    out.println("<h2>Google Search Time</h2>");
    out.println(r.getSearchTime() + " seconds.");
} catch (Exception f) {
    out.println("The call to the Google Web API failed:");
    out.println(f.toString());
}

Results

0.278451 seconds.

Paging Through Results

Although the Google Web Services API only returns 10 results at a time, you can page through the results by setting the starting index:

GoogleSearch s = new GoogleSearch();
s.setKey("H/ufNfpQFHIXOhEAuGHVIRl59K66koWo");
s.setQueryString("peace");
s.setStartResult(42);
try {
    GoogleSearchResult r = s.doSearch();
    out.println("<h2>Google Search Results</h2>");
    out.println(r.toString());
} catch (Exception f) {
    out.println("The call to the Google Web API failed:");
    out.println(f.toString());
}
Results

Similar to the first example's results, with Start Index = 42

Detailed Search Results

You can obtain detailed information about the search results, such as the URL they came from, the title of the documents they were retrieved from, a snippet of HTML code describing the document, and the size of the returned search result:

GoogleSearch s = new GoogleSearch();
s.setKey("H/ufNfpQFHIXOhEAuGHVIRl59K66koWo");
s.setQueryString("prosperity");
try {
    GoogleSearchResult r = s.doSearch();
    out.println("<h2>Google Detailed Search Results</h2>");
    GoogleSearchResultElement[] gsres = r.getResultElements();
    for (int i=0; i<gsres.length; i++)
        out.println(gsres[i].toString());
} catch (Exception f) {
    out.println("The call to the Google Web API failed:");
    out.println(f.toString());
}

Results

Ten formatted paragraphs similar to this one:

  [
  URL  = "http://www.yourprosperity.com.au/"
  Title = "Visitor"
  Snippet = ""
  Directory Category = {SE="", 
  FVN="Top/Regional/Oceania/Australia/Business_and_Economy/Financial_Services/
  Share_Trading/Stockbrokers/Online_Trading"}
  Directory Title = "Your Prosperity"
  Summary = "The subsidiary of MLC Holdings Limited offers services in share 
  trading through JDV, fund trading,..."
  Cached Size = "1k"
  Related information present = true
  Host Name = ""
  ]