1

如何使用 JAVA 使用 Google 自定义搜索 API 的一种方法?Google Search Appliance API 的适当用途是什么?

4

1 回答 1

3

这是谷歌自定义搜索 API 示例。您需要下载库,示例在这里

public class Custom {
public static void main(String args[]) throws IOException  {
        String key="Replace with your API key";
        String qry="batman";// search key word
        URL url = new URL(
                "https://www.googleapis.com/customsearch/v1?               
                key="+key+"&cx="Replace with unique ID"&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(url);
        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);
            }     
        }
        conn.disconnect();   
    }

  }
于 2012-07-27T03:54:02.567 回答