【问题标题】:Java code for using google custom search API使用谷歌自定义搜索 API 的 Java 代码
【发布时间】:2012-04-21 07:54:44
【问题描述】:

任何人都可以分享一些 java 代码以开始使用谷歌搜索 api。我在互联网上搜索但没有找到任何合适的文档或好的示例代码。我发现的代码似乎不起作用。我会的如果有人可以帮助我,谢谢。(我已获得 API 密钥和自定义搜索引擎 ID)。

谢谢。

【问题讨论】:

  • @RanRag:我不认为这是重复的,因为在这里我知道 Google 自定义搜索 API。我唯一要问的是一些好的 Java 代码来开始使用它。

标签: java api google-custom-search


【解决方案1】:

我在上面@Zakaria 提供的代码中更改了while loop。这可能不是解决问题的正确方法,但它为您提供了谷歌搜索的结果链接。您只需要解析输出。看这里,

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();                              
}

希望它也对你有用。

【讨论】:

  • 我得到了链接的详细信息,但你知道有什么方法可以获取从这些链接打开的网页详细信息吗?
  • 这给了我一个 HTTP 错误代码 400。您每天可以进行多少次查询有限制吗?如果有,这个限制是多少?
  • @Pargat 我得到java.io.IOException: Server returned HTTP response code: 403 帮我解决这个问题,我只使用了上面的代码
  • 如何检索此请求的下一页?
【解决方案2】:

对于任何需要使用 Google 库的自定义搜索 API 的工作示例的人,您可以使用此方法:

public static List<Result> search(String keyword){
    Customsearch customsearch= null;


    try {
        customsearch = new Customsearch(new NetHttpTransport(),new JacksonFactory(), new HttpRequestInitializer() {
            public void initialize(HttpRequest httpRequest) {
                try {
                    // set connect and read timeouts
                    httpRequest.setConnectTimeout(HTTP_REQUEST_TIMEOUT);
                    httpRequest.setReadTimeout(HTTP_REQUEST_TIMEOUT);

                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
    List<Result> resultList=null;
    try {
        Customsearch.Cse.List list=customsearch.cse().list(keyword);
        list.setKey(GOOGLE_API_KEY);
        list.setCx(SEARCH_ENGINE_ID);
        Search results=list.execute();
        resultList=results.getItems();
    }
    catch (  Exception e) {
        e.printStackTrace();
    }
    return resultList;
}

此方法返回 Result 对象列表,因此您可以对其进行迭代

    List<Result> results = new ArrayList<>();

    try {
        results = search(QUERY);
    } catch (Exception e) {
        e.printStackTrace();
    }
    for(Result result : results){
        System.out.println(result.getDisplayLink());
        System.out.println(result.getTitle());
        // all attributes:
        System.out.println(result.toString());
    }

如您所见,您必须定义您的自定义 GOOGLE_API_KEY、SEARCH_ENGINE_ID、QUERY 和 HTTP_REQUEST_TIMEOUT,即

private static final int HTTP_REQUEST_TIMEOUT = 3 * 600000;

我使用 gradle 依赖:

dependencies {
compile 'com.google.apis:google-api-services-customsearch:v1-rev57-1.23.0'
}

【讨论】:

  • 感谢您的回答!我实际上正在处理这个问题,并发现您的代码很有用。我喜欢您设置 API 密钥和搜索引擎 ID 的方式,而不是像在其他答案中那样使用 URL 字符串。
【解决方案3】:

嗯,我认为您可以使用 Java RESTFUL 客户端并没有什么特别之处。

我使用 that Java code 并基于 Google documentation 尝试了自定义 API:

public static void main(String[] args) throws IOException {
        URL url = new URL(
                "https://www.googleapis.com/customsearch/v1?key=YOUR-KEY&cx=013036536707430787589:_pqjad5hr1a&q=flowers&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) {
            System.out.println(output);
        }

        conn.disconnect();
    }

您必须将“YOUR-KEY”替换为Google APIs Console 上的一个。

【讨论】:

  • 我运行了代码,但输出与我的预期不符。我想我会从代码中得到一些顶级链接。你能告诉我如何从这段代码中实现吗?
  • @Zakaria 我得到了链接的详细信息,但你知道有什么方法可以获取从这些链接打开的网页详细信息吗?
猜你喜欢
  • 2011-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-14
  • 1970-01-01
  • 1970-01-01
  • 2015-10-18
相关资源
最近更新 更多