2013-12-10 41 views
0

我正在做一個http獲取請求。我需要接收大量數據,但在讀取數據時出現OutOfMemory異常。從http讀取數據時發生OutOfMemory錯誤獲取請求android

我的代碼:

public static String getData(String url) throws CustomException { 
    // http post 
    InputStream is = null; 
    StringBuilder sb = null; 
    String result = null; 
    HttpGet httppost; 
    HttpEntity entity; 

    try { 
     HttpClient httpclient = new DefaultHttpClient(); 
     httppost = new HttpGet(url); 
     HttpResponse response = httpclient.execute(httppost); 
     entity = response.getEntity(); 
     is = entity.getContent(); 
     Log.e("log_tag", "connection success "); 
    } catch (Exception e) { 
     Log.e("log_tag", "Error in http connection" + e.toString()); 
     throw new CustomException("Could not establish network connection"); 
    } 

    // convert response to string 
    try { 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     int c; 
     byte buffer[] = new byte[1024]; 
     while ((c = is.read(buffer)) > -1) 
      baos.write(buffer, 0, c); //**OutOfMemory Exception.** 
     byte[] data = baos.toByteArray(); 

     is.close(); 
     result = new String(data, 0, data.length, "utf-8"); 

    } catch (Exception e) { 
     Log.e("log_tag", "Error converting result " + e.toString()); 
     throw new CustomException("Error parsing the response"); 
    } 

    return result; 

} 

URL我傳遞給的getData是:http://ec2-50-19-105-251.compute-1.amazonaws.com/ad/Upload/getitemlist09122013014749.txt

請建議我如何解決這個問題。

+0

有這麼多的記錄多數民衆贊成爲什麼..我想你應該安裝應用程序在SD卡或手機存儲.. – Riser

+0

老兄,該網址返回大量的數據。不要將它添加到內存中。使用文件系統。 –

回答

2

收到的文件很大,您需要將響應寫入文件而不是ByteArrayOutputStream,然後嘗試解析文件的結果。

如果可能的話,服務器應該將大文件分成小塊。

0

一個可能的解決方案是在從服務器獲取結果時實現分頁。之後,你可以逐漸將數據寫入某處。

相關問題