2013-07-12 42 views
0

我是webservice的新手,我处于学习阶段。没有太多在线内容提供有关使用MovieDB API Web服务的信息。不,我只是专注于试图在屏幕上获得电影信息。如何连接到MovieDB API webservice?

所以按照API我要求的信息和我得到的JSON响应,当我在浏览器中粘贴http://api.themoviedb.org/3/movie/550?api_key=MYKEY

我想写一个使用JAVA,SOAP解析JSON并获取所需信息的web服务。我尝试使用HttpURLConnection,然后使用BufferedReader,但它不工作。

请提出我一些更好的选择。任何链接/博客都会有所帮助。

这是代码片段。

public class TestJSON { 

/** 
* @param args 
*/ 
public static void main(String[] args) { 
    try{ 
     URL url = new URL("http://api.themoviedb.org/3/movie/550?api_key=MYKEY/3/movie/550"); 
     HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
     con.setDoOutput(true); 
     con.setRequestMethod("GET"); 
     con.setRequestProperty("Content-Type", "application/json"); 

     String input = ""; 

     OutputStream os = con.getOutputStream(); 
     os.write(input.getBytes()); 
     os.flush(); 

     if (con.getResponseCode() != HttpURLConnection.HTTP_CREATED) { 
      throw new RuntimeException("Failed : HTTP error code : " 
       + con.getResponseCode()); 
     } 

     BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream()))); 

     String output; 
     System.out.println("Output from Server .... \n"); 
     while ((output = br.readLine()) != null) { 
      System.out.println(output); 
     } 

     con.disconnect(); 


    } 
    catch(MalformedURLException m){ 
     System.out.println("Malformed URL"); 
    } 
    catch(IOException ioe){ 
     System.out.println("IO exception"); 
    } 


} 

}

在此先感谢。

惊鼓

+0

从不害羞,分享你已经尝试的代码。 –

+0

@JunedAhsan谢谢我现在有我的代码。 – quickBongo

+0

你能提一下你得到的错误/异常吗? –

回答

0

试试这个代码来读取URL输出:

BufferedReader in = new BufferedReader(
          new InputStreamReader(conn.getInputStream())); 
String inputLine; 
StringBuffer html = new StringBuffer(); 

while ((inputLine = in.readLine()) != null) { 
    html.append(inputLine); 
} 
in.close(); 
+0

我得到java.lang.RuntimeException:失败:HTTP错误代码:401 – quickBongo

+0

@Zingo你得到的是因为你的令牌/密钥无效。 –

+0

出于安全原因,我无法提供密钥。关键是有效的,当我在网址中插入实际密钥并将其粘贴到浏览器中时,它工作正常。所以我认为关键不是问题。我访问该服务的方式似乎存在一些问题。 – quickBongo