Java OO Wrapper for Google AJAX API
UPDATE: I’ve moved source code to GitHub
General information
Some time ago I discovered question of using Google AJAX API from Java programs and, as visiting statistic of my blog showed, search query “google+API+java” is very popular. This post is #1 for my blog
So I decided to continue investigation of this topic and write some simple wrapper around “raw” HTTP request/response handling. And here you can find results of my work.
First of all I’d like to notice that this code was written for “personal” usage and I’ll be really happy if it’ll be useful for someone else. If you have some questions/concerns/bug repors regarding this wrapper, please fill free to contact me. This will help a lot.
General idea
The main idea of this wrapper (as any other wrapper) is to hide all details of using Google AJAX API in straight way. With it you just need to customize your search and call appropriate search method.
Search results are returned in the form of JSON objects. Google’s gson is used to make JSON->Java object’s conversation. Java classes that represent JSON ones were created manually
(if someone now better way please tell me
) and is based on official Google’s docs. The biggest drawback of this that it’s needed to keep this classes conformity by hand.
Source code
If you want to take a look at initial implementation of wrapper please download this archive GoogleAPIHelper or get it from GitHub.
Current version supports only web search and is in development state. So use it carefully.
Required libraries:
Usage examples
1. Searching web and getting all result (60 max as experiments showed)
package ua.org.vera.googleApiHelper.test; import ua.org.vera.googleApiHelper.Googler; import ua.org.vera.googleApiHelper.Response; import ua.org.vera.googleApiHelper.GsearchResult; import ua.org.vera.googleApiHelper.Googler.SearchError; import com.google.gson.Gson; public class GoogleAJAXSearchAPI { private static String searchString = "vera"; public static void main(String[] args){ String result = null; int current = 0; int max = 60; Gson gson = new Gson(); try { do { //call main search method: specify what to search and start result result = Googler.searchWeb(searchString, current); Response response = gson.fromJson(result, Response.class); for (GsearchResult gsearchResult : response.getResponseData().getResults()) { System.out.println("Result url #" + current + ":" +gsearchResult.getUrl()); current++; } } while(current < max); } catch (SearchError e) { e.printStackTrace(); } } }