Reputation: 73
Require your Help for fetching the json response from the httpclient in Android since the following code mentioned is making the Application to crash on android Devices particularly on the GingerBread device , since the JSON Response is very huge in size (may be 7 MB) . So I wanted to know any alternative way for reading the JSONresponse from the Httpclient, since the present implementation is consuming too much of memory and making my application to crash on lower end devices.
It would be very greatful for any suggestions or help for solving this problem .
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();
}
Upvotes: 1
Views: 691
Reputation: 27538
Google Android ships with an extremely outdated fork of Apache HttpClient. However, the base principles still apply. The most efficient way of processing HTTP responses with Apache HttpClient is by using a ResponseHandler
. See my answer to a similar question for details
Upvotes: 1
Reputation: 8680
You can use Google Volley for you networking. Among a lot of other things, it has a built in method to retrieve JSON objects, regardless of size.
Give it a try.
Upvotes: 1
Reputation: 629
You could try this:
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);
}
}
Upvotes: 1