2013-08-28 25 views
1

要求您的幫助從Android中的httpclient獲取json響應,因爲下面提到的代碼會導致應用程序在android設備上崩潰,尤其是在GingerBread設備上,因爲JSON響應的規模非常巨大(可能爲7 MB)。 所以我想知道從Http客戶端讀取JSON響應的另一種方式,因爲目前的實現消耗了太多的內存,並使我的應用程序在低端設備上崩潰。從Android中的Httpclient讀取大量數據(7MB或更多)時需要幫助

對於解決此問題的任何建議或幫助將非常有幫助。

HttpClient httpClient = new DefaultHttpClient(ccm, params); 
HttpGet httpGet = new HttpGet(url); 
httpGet.setHeader("Cache-Control", "no-cache; no-store"); 
HttpResponse httpResponse = httpClient.execute(httpGet); 

response = Utils.convertStreamToString(httpResponse.getEntity().getContent()); 
public static String convertStreamToString(InputStream is) 
    { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
     StringBuilder sb = new StringBuilder(); 

     String line = null; 
     try { 
      while ((line = reader.readLine()) != null) { 
       //System.gc(); 
       sb.append(line).append("\n"); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       is.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return sb.toString(); 
    } 
+0

這是一個圖像或PDF文件? – Ansar

+0

這是一個只是txt文件,大約6.2 Mb,主要問題發生在下面一行while((line = reader.readLine())!= null){ sb.append(line).append(「\ n 「); } –

+0

是響應是一個json數組? – Ansar

回答

1

可以使用Google Volley爲你的網絡。在很多其他方面,它有一個內置的方法來檢索JSON對象,無論大小如何。

試試看。

1

你可以試試這個:

public static String convertStreamToString(InputStream is) 
{ 
    try 
    { 
     final char[] buffer = new char[0x10000]; 
     StringBuilder out = new StringBuilder(); 
     Reader in = new InputStreamReader(is, "UTF-8"); 
     int read; 
     do 
     { 
     read = in.read(buffer, 0, buffer.length); 
     if (read > 0) 
     { 
      out.append(buffer, 0, read); 
     } 
     } while (read >= 0); 
     in.close(); 
     return out.toString(); 
    } catch (IOException ioe) 
    { 
     throw new IllegalStateException("Error while reading response body", ioe); 
    } 
} 
+0

但它沒有按預期工作,而是它給出了內存溢出 –

1

Google Android附帶了一個非常過時的Apache HttpClient分支。但是,基本原則仍然適用。使用Apache HttpClient處理HTTP響應的最有效方式是使用ResponseHandler。請參閱我的answer對相似的問題的詳細信息