谷歌搜索以编程方式使用Java

时间:2016-10-21 16:21:01

标签: java google-search google-search-appliance

我可以使用Java代码执行Google搜索吗?例如,如果我搜索“纽约”,它会向我发送以结构化方式显示所有信息的数据,例如JSON或XML数据吗?你能否分享一下代码,或者给我任何能做到这一点的API?

1 个答案:

答案 0 :(得分:3)

Google知识搜索的示例代码。

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

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

}