2013-06-18 68 views
0

我試圖使用Google feed api獲取一些數據。但是line = reader.readLine()始終爲空。使用Google feed api java

URL url = new URL("https://ajax.googleapis.com/ajax/services/feed/find?" + 
        "v=1.0&q=Official%20Google%20Blog"); 
      URLConnection connection = url.openConnection(); 
      String line; 
      StringBuilder builder = new StringBuilder(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
      while((line = reader.readLine()) != null) { 
      builder.append(line); 
      } 

      JSONObject json = new JSONObject(builder.toString()); 
+0

如何知道它的null,試着在你的while循環中打印'line'並檢查實際將要發生的事情 –

+0

我使用調試器進行了檢查。 –

+0

我試過你的代碼,我能夠在沒有任何修改的情況下獲取數據。我建議你在你的while循環中放一個打印語句並檢查。 –

回答

1

試試這個

URL url = new URL("https://ajax.googleapis.com/ajax/services/feed/find?" + 
      "v=1.0&q=Official%20Google%20Blog"); 
    URLConnection connection = url.openConnection(); 

    ByteArrayOutputStream content = new ByteArrayOutputStream(); 

    InputStream is = connection.getInputStream(); 
    int len = 0; 
    byte[] buffer = new byte[1024]; 
    while ((len = is.read(buffer)) >= 0) 
    { 
     content.write(buffer, 0, len); 
    } 
    byte[] finalContent = content.toByteArray(); 
    String str = new String(finalContent, "UTF8"); 
    System.out.print(str); 

或者其他方式,你可以閱讀content-length頭和讀取,直到你得到這麼多的數據。

+0

我發現logcat沒有打印整個數據。不管怎麼說,還是要謝謝你。 –