2012-10-12 29 views
1

我想讀遊離鹼查詢與Java的結果:Java的遊離鹼查詢

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) 

我已經做了這之前(與其他請求),它的工作,所以這裏有什麼問題?

+0

400意味着不好請求 – PbxMan

回答

1

If've got it !!!

的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(" ", "")); 
+0

不錯! +1爲那 – jozefg

+0

爲什麼不只是URLEncode它將允許空格,而不會破壞字符串值內潛在的正確空間(我試過這個) –

+0

你是對的,但我試過了,用URLEncode和Apache encodeQuery,URL格式不正確對於這個api並且不接受某些地方的空間。 – PbxMan

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編碼的查詢字符串參數。

+0

謝謝你們,它工作得很好。但是,當我連續做很多查詢時,我有一些錯誤,這是正常的嗎? – Scipion

+0

你的意思是幾個短期內(谷歌強加的費率限制)還是一個包含大量信息的大型查詢(最大HTTP GET大小)? –

+0

幾個在短時間內。 (試圖讓麥當娜的朋友,然後是馬當娜朋友的朋友,......)。 – Scipion