1

我正在尝试使用 Java 读取 freebase 查询的结果:

URL url = null;
String inputLine;

try{
  url = new URL("https://www.googleapis.com/freebase/v1/mqlread?query={\"id\":\"/en/madonna\", \"name\": null, \"type\":\"/base/popstra/celebrity\",\"/base/popstra/celebrity/friendship\": [{\"participant\": [] }] }");

} catch (MalformedURLException e) {
  e.printStackTrace();
}
BufferedReader in;
try {
  URLConnection con = url.openConnection();
  con.setReadTimeout( 1000 ); //1 second
  in = new BufferedReader(new InputStreamReader(con.getInputStream()));
  while ((inputLine = in.readLine()) != null) {
  System.out.println(inputLine);
}
in.close();

} catch (IOException e) {
  e.printStackTrace();
}

但是,我收到以下错误:

java.io.IOException: Server returned HTTP response code: 400 for URL:     https://www.googleapis.com/freebase/v1/mqlread?query={ "id":"/en/madonna", "name": null, "type": "/base/popstra/celebrity","/base/popstra/celebrity/friendship": [{ "participant": [] }] }

at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at FreebaseCelebrities.main(FreebaseCelebrities.java:66)

我之前已经这样做了(有其他请求)并且它有效,那么这里有什么问题?

4

2 回答 2

1

如果有的话!!!

api没有正确解析emply空格使用这个:

    url = new URL("https://www.googleapis.com/freebase/v1/mqlread?query={\"id\":\"/en/madonna\", \"name\": null, \"type\":\"/base/popstra/celebrity\",\"/base/popstra/celebrity/friendship\": [{\"participant\": [] }] }".replace(" ", ""));
于 2012-10-12T20:06:30.570 回答
1

创建 URL 时尝试以下代码:

try {
  String query = "{\"id\":\"/en/madonna\", \"name\": null, \"type\":\"/base/popstra/celebrity\",\"/base/popstra/celebrity/friendship\": [{\"participant\": [] }] }";
  url = new URL("https://www.googleapis.com/freebase/v1/mqlread?query="+URLEncoder.encode(query, "UTF-8"));
} catch (UnsupportedEncodingException e) {
  e.printStackTrace();
} catch (MalformedURLException e) {
  e.printStackTrace();
}

您需要对查询字符串参数进行 URL 编码。

于 2012-10-12T20:21:12.070 回答