【问题标题】:what is kgsearch.properties? Cant apply google knowledge graph API using Java什么是 kgsearch.properties?无法使用 Java 应用谷歌知识图谱 API
【发布时间】:2017-03-03 14:41:50
【问题描述】:

这是我在 Eclipse 上执行的代码 它是从这里复制的: https://developers.google.com/knowledge-graph/

安装所有库后,程序可以成功编译,但程序终止 java.io.FileNotFoundException:kgsearch.properties(没有这样的文件或目录)错误。如何让以下示例代码在我的 eclipse 上运行?

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;

import com.jayway.jsonpath.JsonPath;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import java.io.FileInputStream;
import java.util.Properties;

public class mainS {
  public static Properties properties = new Properties();
  public static void main(String[] args) {
    try {
      properties.load(new FileInputStream("kgsearch.properties"));

      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", "Taylor Swift");
      url.put("limit", "10");
      url.put("indent", "true");
      url.put("key", properties.get("API_KEY"));
      HttpRequest request = requestFactory.buildGetRequest(url);
      HttpResponse httpResponse = request.execute();
      JSONObject response = (JSONObject) parser.parse(httpResponse.parseAsString());
      JSONArray elements = (JSONArray) response.get("itemListElement");
      for (Object element : elements) {
        System.out.println(JsonPath.read(element, "$.result.name").toString());
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}

【问题讨论】:

    标签: java eclipse google-knowledge-graph


    【解决方案1】:

    是的,因为kgsearch.properties 可能不存在。 创建文件并在此处输入您的 API_KEY。 该文件应类似于

    API_KEY = <your_key_here>

    创建并保存文件后,使用以下代码 sn-p

    File file = new File("C:/your/path/here/", "kgsearch.properties");
    properties.load(new FileInputStream(file));
    

    它应该在后面起作用

    阅读类似的问题here 和示例here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-27
      • 2022-11-29
      • 1970-01-01
      • 1970-01-01
      • 2012-12-15
      • 2010-10-20
      • 2018-08-19
      • 1970-01-01
      相关资源
      最近更新 更多