gpt4 book ai didi

使用谷歌自定义搜索 API 的 Java 代码

转载 作者:搜寻专家 更新时间:2023-10-30 21:19:33 25 4
gpt4 key购买 nike

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

谢谢。

最佳答案

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

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

希望它对你也有用。

关于使用谷歌自定义搜索 API 的 Java 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10257276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com