2013-12-15 29 views
0

我目前正在使用android,並且我正在使用帶有一些頭部的http連接(我還沒有包含它們或者出於安全目的的真實網址)從API獲取JSON響應,該響應返回到應用程序中。我遇到的問題是,當使用http請求的getContentLength方法時,將返回錯誤的長度(返回的錯誤長度爲1225,JSON數組的字符長度正確爲3365)。getContentLength返回1225,真實長度3365

我有一種感覺,即當我的閱讀器開始閱讀它時,JSON並未完全加載,因此只讀取當時加載的JSON。有沒有辦法解決這個問題,可能在HTTP連接上使用延遲或等到它完全加載以讀取數據?

  URL url = new URL("https://www.exampleofurl.com"); 
      HttpURLConnection request = (HttpURLConnection) url.openConnection();    

      request.connect(); 
      int responseCode = request.getResponseCode(); 

      if(responseCode == HttpURLConnection.HTTP_OK) { 

       InputStream inputStream = request.getInputStream(); 
       InputStreamReader reader = new InputStreamReader(inputStream); 

       long contentLength2 = Long.parseLong(request.getHeaderField("Content-Length")); 

       Log.i("contentLength: ", "Content: " + contentLength2); 

回答

0

我一般不建議總是依靠「內容長度」,因爲它可能無法使用(你得-1),或者是受中間代理。

你爲什麼不剛剛看了你的流,直到它耗盡到內存緩衝區(比如,StringBuilder),然後獲得實際的大小,例如:

BufferedReader br = new BufferedReader(inputStream); // inputStream in your code 
String line; 
StringBuilder sb = new StringBuilder(); 
while ((line = br.readLine()) != null) { 
    sb.append(line); 
} 
// finished reading 
System.out.println("data size = " + sb.length()); 
JSONObject data = new JSONObject(sb.toString()); 

// and don't forget finally clauses with closing streams/connections 
+0

你是一個紳士和學者先生!完美的作品!我試圖給你投票,但是它說我需要15個聲望:/這就像學校重來一遍。 非常感謝! –