将新的Freebase API与java客户端一起使用

时间:2012-03-23 16:17:36

标签: java freebase

到目前为止,我一直在玩google-api for java,所以我可以从freebase获取一些数据。我成功使用了mqlread。现在,我想尝试一下文本服务。麻烦的是,我似乎在文档中遗漏了一些东西。我无法弄清楚如何使用Freebase.Text.get(List id)。

我应该在List id参数上输入什么?我试过以下内容:

    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    JsonHttpRequestInitializer requestInitializer = new JsonHttpRequestInitializer() {
        public void initialize(JsonHttpRequest jsonHttpRequest) throws IOException {
            FreebaseRequest freebaseRequest = (FreebaseRequest) jsonHttpRequest;
            freebaseRequest.setPrettyPrint(true);
        }
    };

    Freebase freebase = Freebase.builder(httpTransport, jsonFactory).setJsonHttpRequestInitializer(requestInitializer).build();
    ArrayList<String> list = new ArrayList<String>();

    JSONObject j = new JSONObject();
    j.put("id", "en/bob_dylan");
    list.add(j.toJSONString());
    Freebase.Text.Get text = freebase.text().get(list);
    ContentserviceGet get = text.execute();
    System.out.println(get.toPrettyString());

list.add("en/linux_kernel");

两个案件都返回404.感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

我没有玩过Java api,但这里有两个可能对你有帮助的例子。

API Explorer http://code.google.com/apis/explorer/#_s=freebase&_v=v1-sandbox&_m=text.get&id=en/bob_dylan

批处理请求的示例(这是一个json示例) http://wiki.freebase.com/wiki/ApiText#Batch_Requests

请注意,id字段不以/ - 开头,例如上例中的id = en / bob_dylan。

或者,您可以将其作为数组传递id = [“en”,“bob_dylan”]

希望这有效。

答案 1 :(得分:0)

适用于Java的Google Freebase API存在问题。我找到了问题的原因并输入了以下问题: http://code.google.com/p/google-api-java-client/issues/detail?id=493

使用API​​的预期方式是这样的,但它不起作用:

ContentserviceGet result = freebase.text().get(Arrays.asList("en", "avenue_q")).execute();

答案 2 :(得分:0)

您不必通过List,id传递JSON字符串,因为简单的字符串类型将完成工作。以下是获取文本的代码:

    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    HttpRequestInitializer httpRequestInitializer = new HttpRequestInitializer() {
        @Override
        public void initialize(HttpRequest arg0) throws IOException {
            // TODO Auto-generated method stub
        }
    };
    JsonHttpRequestInitializer requestInitializer = new JsonHttpRequestInitializer() {
        public void initialize(JsonHttpRequest jsonHttpRequest) throws IOException {
            FreebaseRequest freebaseRequest = (FreebaseRequest) jsonHttpRequest;
            freebaseRequest.setPrettyPrint(true);
        }
    };
    Freebase.Builder fbb = new  Freebase.Builder(httpTransport, jsonFactory, httpRequestInitializer);
    Freebase freebase = fbb.setJsonHttpRequestInitializer(requestInitializer).build();
    ArrayList<String> list = new ArrayList<String>();
    try {
        list.add("/en/bob_dylan");
        Freebase.Text.Get text = freebase.text().get(list);
        ContentserviceGet get = text.execute();
        System.out.println(get.toPrettyString());
    } catch (Exception e) {
        e.printStackTrace();
    }