Search code examples
javagoogle-apigoogle-custom-search

Google Search with Java


I am looking into a solution to automate Google Searches using Java. I have looked into the Google Custom Search API but it does not appear to fulfill the requirements. It appears Custom Search requires the domains to be specified ahead of time which does not work for me because I don't know the domains. We want to do a Google Web search, like you would from your browser. Is this possible with the Google Custom Search API? If not does anyone know of any api / library, preferable in Java that would work?


Solution

  • public static void main(String[] args) {
        String googleAJAX = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
        String searchFor = "stuff";
    
        /**
            **Edit:** of course you can also get user input as a string
            and search for that instead. i.e.:
            String searchFor = (new Scanner(System.in)).nextLine();
        **/        
    
        URL url = new URL(googleAJAX + URLEncoder.encode(searchFor, "UTF-8"));
        Reader read = new InputStreamReader(url.openStream(), "UTF-8");
        GoogleResults results = new Gson().fromJson(read, GoogleResults.class);
    
        // Return results (title and URL)
        System.out.println(results.getResponseData().getResults().get(0).getTitle());
        System.out.println(results.getResponseData().getResults().get(0).getUrl());
    }