如何在java中使用新的freebase api(api search)?

时间:2012-06-05 10:30:10

标签: java freebase

我无法理解这个API。我已下载(maven)google-api-services-freebase并测试我已尝试执行此代码:

 JsonHttpRequestInitializer initializer = 
        new GoogleKeyInitializer("MY KEY");
                                 HttpTransport httpTransport = new NetHttpTransport();
                                 JsonFactory jsonFactory = new JacksonFactory();

 Freebase freebase = 
          Freebase.builder(httpTransport,   
          jsonFactory).setJsonHttpRequestInitializer(initializer).build();

现在我想这样做:

https://www.googleapis.com/freebase/v1/search?query=cardiff&lang=en&type=university

接下来,我想解析json输出。

请问,freebase对象中的方法在哪里?我看到 freebase.mqlread freebase.text 但是我找不到类似于API SEARCH的任何方法(http://wiki.freebase.com/wiki/ApiSearch)。< / p>

2 个答案:

答案 0 :(得分:4)

不幸的是,Java API Client还不支持Freebase Search。以下是使用Apache HttpClient进行搜索的方法。

HttpClient httpclient = new DefaultHttpClient();
JSONParser parser = new JSONParser();

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("query", "Blue Bottle"));
params.add(new BasicNameValuePair("key", API_KEY));

String serviceURL = "https://www.googleapis.com/freebase/v1/search";
String url = serviceURL + "?" + URLEncodedUtils.format(params, "UTF-8");      
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
JSONObject response = (JSONObject)parser.parse(EntityUtils.toString(httpResponse.getEntity()));
JSONArray results = (JSONArray)response.get("result");

for (Object result : results) {
  System.out.println(JsonPath.read(result,"$.name").toString());
}

此代码还使用json-simplejson-path库。

答案 1 :(得分:3)

谢谢。

这是我的代码:

import com.google.gson.*;
import org.apache.http.*;

//...

public static void searchTest(String query, String key, String params) throws IOException
{        
       String query_envelope = "{\"query\":" + query + "}";
       String service_url = "https://www.googleapis.com/freebase/v1/search";      

       String url = service_url    + "?query=" + URLEncoder.encode(query, "UTF-8")
                                    + params 
                                    + "&key=" + key;     

       HttpClient httpclient = new DefaultHttpClient();   
       HttpResponse response = httpclient.execute(new HttpGet(url));  

       JsonParser parser = new JsonParser();
       JsonObject json_data = 
       (JsonObject)parser.parse(EntityUtils.toString(response.getEntity()));
       JsonArray results = (JsonArray)json_data.get("result");            

       if(results != null)
       {
           for (Object planet : results) 
           {
              System.out.println(((JsonObject)planet).get("name"));
           }
       }        
}