求解並修改了代碼。無法訪問java中的API數據和JSON解析錯誤
我想從腐爛的番茄API檢索數據使用java,它是一個簡單的聊天機器人。我的URI在我的瀏覽器中粘貼時起作用。但我的代碼沒有返回相同的結果,我不知道我做錯了什麼。
第二個問題是我的'JsonReader'無法解析爲類型,我沒有選擇導入它。我一直在使用this guide!
代碼如下:
String url = http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=queryText&page_limit=10&page=1&apikey=[]
try {
urlObj = new URL(url); //The URI to be used.
con = (HttpURLConnection) urlObj.openConnection(); //OPen a connection to the URI
//int responseCode = con.getResponseCode();
//System.out.println("\nSending 'GET' request to URL : " + url);
//System.out.println("Response Code : " + responseCode);
scan = new Scanner(urlObj.openStream());
String strResultSet = "";
while (scan.hasNext()) {
strResultSet+= scan.nextLine();
}
//System.out.println("StrJson"+strResultSet);
JSONObject JSONResultSet = new JSONObject(strResultSet);
JSONArray results = JSONResultSet.getJSONArray("movies");
JSONObject firstResult = results.getJSONObject(0);
movie.setTitle(firstResult.getString(KEY_TITLE));
movie.setId(firstResult.getString(KEY_ID));
con.disconnect();
scan.close();
當然,上面的JSON並不完整,也不會解析。這是你收到的,還是僅僅是一個樣本? – 2014-10-11 12:23:21
「默認回覆」是什麼意思?我希望你用你的實際API密鑰替換你的URL中的括號。 – 2014-10-11 12:29:17
上面的JSON只是一個示例。 movies數組包含許多JSON對象。默認情況下,我的意思是[文檔中顯示](http://developer.rottentomatoes.com/docs/read/Home),是的,我一直在刪除尖括號。 – 2014-10-11 13:06:53