使用 google 自定义搜索 API 的 Java 代码 [英] Java code for using google custom search API

查看:31
本文介绍了使用 google 自定义搜索 API 的 Java 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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).

谢谢.

推荐答案

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

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

希望它也适用于您.

这篇关于使用 google 自定义搜索 API 的 Java 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆