2014-10-11 75 views
0

求解並修改了代碼。無法訪問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(); 
+1

當然,上面的JSON並不完整,也不會解析。這是你收到的,還是僅僅是一個樣本? – 2014-10-11 12:23:21

+0

「默認回覆」是什麼意思?我希望你用你的實際API密鑰替換你的URL中的括號。 – 2014-10-11 12:29:17

+0

上面的JSON只是一個示例。 movies數組包含許多JSON對象。默認情況下,我的意思是[文檔中顯示](http://developer.rottentomatoes.com/docs/read/Home),是的,我一直在刪除尖括號。 – 2014-10-11 13:06:53

回答

0

我解決了使用掃描儀對象遍歷結果集的問題。

scan = new Scanner(urlObj.openStream()); 
String strResultSet = ""; 
while (scan.hasNext()) { 
    strResultSet+= scan.nextLine(); 
} 
0

我不知道這是怎麼編譯。你似乎試圖從你的「url」字符串中獲得一個InputStream。

你應該在HttpURLConnection的調用的getConnection(),如con.getInputStream()

此外,您打印,但實際上沒有檢查responseCode。它可能並不總是表示成功。

下面是http://www.tbray.org/ongoing/When/201x/2012/01/17/HttpURLConnection

'無效的get(網址URL)一個很好的例子{

//這確實沒有網絡IO HttpURLConnection的康恩= url.openConnection(); InputStream in; int http_status; 嘗試{

// this opens a connection, then sends GET & headers 
in = conn.getInputStream(); 

// can't get status before getInputStream. If you try, you'll 
// get a nasty exception. 
http_status = conn.getResponseCode(); 

// better check it first 
if (http_status/100 != 2) { 
    // redirects, server errors, lions and tigers and bears! Oh my! 
} 

}趕上(IOException異常E){// 可怕的事情發生了,在網絡錯誤,或者你 //愚蠢稱爲getResponseCode()之前HUC準備。 //現在基本上沒有關於「conn」的方法,所以不要去 //在那裏尋找幫助。 }

嘗試{ //現在您可以嘗試使用數據 try_reading(in); } catch(IOException e){Network-IO lions and tigers and bear!天啊! }終於{ //像媽媽說的那樣並且保持良好的衛生習慣。 conn.disconnect(); } }`