Java code for using google custom search API

dark_shadow picture dark_shadow · Apr 21, 2012 · Viewed 25.8k times · Source

Can anyone please share some java codes for getting started with google search api's.I searched on Internet but not found any proper documentation or good sample codes.The codes which I found doesn't seem to be working.I'll be thankful if anyone can help me.(I have obtained API key and custom search engine id).

Thanks.

Answer

Pargat picture Pargat · Jun 27, 2012

I have changed the while loop in the code provided by @Zakaria above. It might not be a proper way of working it out but it gives you the result links of google search. You just need to parse the output. See here,

public static void main(String[] args) throws Exception {

    String key="YOUR KEY";
    String qry="Android";
    URL url = new URL(
            "https://www.googleapis.com/customsearch/v1?key="+key+ "&cx=013036536707430787589:_pqjad5hr1a&q="+ qry + "&alt=json");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "application/json");
    BufferedReader br = new BufferedReader(new InputStreamReader(
            (conn.getInputStream())));

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {

        if(output.contains("\"link\": \"")){                
            String link=output.substring(output.indexOf("\"link\": \"")+("\"link\": \"").length(), output.indexOf("\","));
            System.out.println(link);       //Will print the google search links
        }     
    }
    conn.disconnect();                              
}

Hope it works for you too.