2013-07-31 48 views
1

我正在做兩個具有相同代碼的鏈接的簡單JSON抓取。我在兩個不同的時間做這件事,所以我的問題的原因不是因爲他們碰到對方或什麼東西。抓取JSON從一個鏈接工作,而不是從另一個鏈接

這裏是我的代碼:

@Override 
     protected String doInBackground(Object... params) { 
      try { 
       URL weatherUrl = new URL("my url goes here"); 
       HttpURLConnection connection = (HttpURLConnection) weatherUrl 
         .openConnection(); 
       connection.connect(); 

       responseCode = connection.getResponseCode(); 
       if (responseCode == HttpURLConnection.HTTP_OK) { 
        InputStream inputStream = connection.getInputStream(); 
        Reader reader = new InputStreamReader(inputStream); 
        int contentLength = connection.getContentLength(); 
        char[] charArray = new char[contentLength]; 
        reader.read(charArray); 
        String responseData = new String(charArray); 
Log.v("test", responseData); 

當我嘗試這樣搭配:

http://www.google.com/calendar/feeds/[email protected]/public/full?alt=json

我得到具有-1

數組lenth此鏈接的錯誤:

http://api.openweathermap.org/data/2.5/weather?id=5815135

它返回正常,我得到所有的JSON日誌。有誰知道爲什麼?

注意:我嘗試在調試模式下通過我的代碼,但我無法捕捉任何東西。我還下載了一個Google chrome擴展,用於在瀏覽器中解析json,並且這兩個url看起來完全有效。我沒有想法。

回答

3

登錄此:int contentLength = connection.getContentLength();

我沒有看到谷歌的網址返回content-length頭。

如果你只是想從一個URL字符串輸出,你可以使用ScannerURL像這樣:

Scanner s = new Scanner(new URL("http://www.google.com").openStream(), "UTF-8").useDelimiter("\\A"); 
out = s.next(); 
s.close(); 

(不要忘了嘗試/ finally塊和異常處理)

的時間越長路(它允許進度報告等):

String convertStreamToString(InputStream is) throws UnsupportedEncodingException { 

     BufferedReader reader = new BufferedReader(new  
           InputStreamReader(is, "UTF-8")); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     try { 
      while ((line = reader.readLine()) != null) 
       sb.append(line + "\n"); 
     } catch (IOException e) { 
      // Handle exception 
     } finally { 
      try { 
       is.close(); 
      } catch (IOException e) { 
       // Handle exception 
      } 
     } 
     return sb.toString(); 
    } 
} 

然後調用String response = convertStreamToString(inputStream);

+0

你的意思是第一個網址? – darrengorman

+0

正確。並糾正。 – 323go

+0

天氣json的內容長度爲400+,而google json的內容長度爲-1 ...那對我來說意味着什麼?它如何不拾取內容? – EGHDK