2013-07-31 118 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