Java code for using google custom search API

前端 未结 3 1263
遇见更好的自我
遇见更好的自我 2020-12-08 17:25

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

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 17:54

    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.

提交回复
热议问题