Call Google Search API in Java

We will need gogole-gson, a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

package google_search;
 
import com.google.gson.Gson;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
 
public class Google_Search { 
 
    public static void main ( String[] args ) throws Exception { 
        GetGoogleResults("programming");
    }
 
    private static void GetGoogleResults(String term) throws Exception { 
        String google; String charset = "UTF-8"; 
        URL url; Reader reader; 
        Google results;
 
        google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=8&q=";
 
        url = new URL(google + URLEncoder.encode(term, charset));
        reader = new InputStreamReader(url.openStream(), charset);
        results = new Gson().fromJson(reader, Google.class);
 
        if(results.getResponseData()!=null)
        {
            for(int i=0;i<results.getResponseData().getResults().size();i++)
            {
                System.out.println("Title: " + results.getResponseData().getResults().get(i).getTitle());
                System.out.println("Url: " + URLDecoder.decode(results.getResponseData().getResults().get(i).getUrl(), "UTF-8"));
                System.out.println("Content: " + results.getResponseData().getResults().get(i).getContent());
                System.out.println();
            }
        }
    }
}
 
class Google 
{
    private ResponseData responseData;
    public ResponseData getResponseData() { return responseData; }
    public void setResponseData(ResponseData responseData) { this.responseData = responseData; }
 
    static class ResponseData 
    {
        private List<Result> results;
        public List<Result> getResults() { return results; }
        public void setResults(List<Result> results) { this.results = results; }
    }
 
    static class Result 
    {
        private String url;
        private String titleNoFormatting;
        private String content;
        public String getUrl() { return url; }
        public String getTitle() { return titleNoFormatting; }
        public String getContent() { return content; }
        public void setUrl(String url) { this.url = url; }
        public void setTitle(String title) { this.titleNoFormatting = title; }
        public void setContent(String content) { this.content = content; }
    }
}
Categories: Java Tags: , , , ,
%d bloggers like this: