2014-10-11 69 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(); } }`