4

I'm using the following code to get the string representation of server response. The problem is that it's throwing an out of memory exception when it tries to pass the response toString(). This code is running on Android.

String resp = IOUtils.toString(resEntity.getContent(), "UTF-8");

HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("Accept", "JSON");

HttpResponse httpResponse = httpclient.execute(httpGet);
HttpEntity resEntity = httpResponse.getEntity();
if (resEntity != null) {
  //String resp = EntityUtils.toString(resEntity);
  String resp = IOUtils.toString(resEntity.getContent(), "UTF-8"); // exception here
  Log.i(TAG, resp);
// ........
// gosn parser code here
// ........
}

The stacktrace is:

java.lang.OutOfMemoryError: (Heap Size=47395KB, Allocated=36544KB)
at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:94)
at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:124)
at java.lang.StringBuilder.append(StringBuilder.java:271)
at org.apache.commons.io.output.StringBuilderWriter.write(SourceFile:138)
at org.apache.commons.io.IOUtils.copyLarge(SourceFile:2002)
at org.apache.commons.io.IOUtils.copyLarge(SourceFile:1980)
at org.apache.commons.io.IOUtils.copy(SourceFile:1957)
at org.apache.commons.io.IOUtils.copy(SourceFile:1907)
at org.apache.commons.io.IOUtils.toString(SourceFile:778)
at org.apache.commons.io.IOUtils.toString(SourceFile:803)
Joshua Taylor
  • 80,876
  • 9
  • 135
  • 306
Sam
  • 5,427
  • 7
  • 64
  • 78
  • This code isn't causing the OOM, unless you're downloading a large file (in which case you may need to download it to a file and read the file in chunks). Something else is using your memory. – Gabe Sechan Aug 19 '13 at 14:40
  • how big is your json? – njzk2 Aug 19 '13 at 14:40
  • I'm building a android app which is collection of widgets, each widget properties can change from CMS, When the application start it's downloading the all the widget changes and store in the SQLite data base. In that case I cannot exactly say what's the file size. Also this app use set of images saved in database to show as app backgorund images, Is there any way that i can read chunk of response – Sam Aug 19 '13 at 14:48

0 Answers0