java - 以编程方式使用 Java 的 Google 搜索

标签 java google-search google-search-appliance

我可以使用 Java 代码执行 Google 搜索吗?例如,如果我搜索“纽约”,它会向我发送以结构化 方式说明所有信息的数据,例如 JSON 或 XML 数据吗?您能否分享代码或给我任何执行此操作的 API?

最佳答案

谷歌知识搜索的示例代码。

使用 https://console.developers.google.com/apis/dashboard 生成 API > 凭据 > 创建凭据 > API key

import java.util.List;

import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;

@Service
public class GoogleSearchService {


    @Async
    public void searchGoogle(List<String> keywords){
        try {
            ObjectMapper mapper = new ObjectMapper();
            HttpTransport httpTransport = new NetHttpTransport();
            HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
            JSONParser parser = new JSONParser();
            GenericUrl url = new GenericUrl("https://kgsearch.googleapis.com/v1/entities:search");
            url.put("query", "Kolkata");
            url.put("limit", "1");
            url.put("indent", "true");
            url.put("key", "xxxxxx");
            HttpRequest request = requestFactory.buildGetRequest(url);
            HttpResponse httpResponse = request.execute();
            String responseString = httpResponse.parseAsString();

            JsonNode node = mapper.readTree(responseString).get("itemListElement").get(0).get("result");
            System.out.println(node.get("name"));
            System.out.println(node.get("@type"));
            System.out.println(node.get("detailedDescription").get("articleBody"));

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}

关于java - 以编程方式使用 Java 的 Google 搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40181330/

相关文章:

java - 如何获取 Multipart 文件的真实扩展类型

java - 修改方法,使参数可以是实现 Comparable 的任何类型

Java:如何对数组元素进行双重检查锁定?

google-search - Google 是否提供搜索 API

没有网页的 Android 应用索引

javascript - 如果 Google 的主页如此之小,为什么源代码有数百行代码?

java - 在 Google 连接器安装程序中的何处查找文件系统连接器的日志

.net - 将 Google Search Appliance 结果实现到网站中

java - 将信息从一个 mysql 表插入到另一个表

mysql - Google Search Appliance 索引 MySQL 数据库