简体   繁体   中英

Code stuck at EntityUtils.toString and keeps waiting for ages

I am sending some data to server from my android device and in return getting Json Response back from the server.The Data returned is a quite large chunk of data (Multiple Images precisely) . I am echoing the statusCode returned from the Server and it is 200. but The JAVA code keeps on waiting on a statement

objHttpEntity = objHttpResponse.getEntity();
statusCode=objHttpResponse .getStatusLine().getStatusCode();
String responseDataString = EntityUtils.toString(objHttpEntity);//this statement

and in logs, I see my garbage collector running,getting the memory back from the resources to accomodate the currently received data. In devices having RAM 1GB or less, the application is crashing abruptly giving out an OutOfMermoryException .But in devices having RAM more than the latter, the application waits, and waits, and waits and finally execute the rest of the consecutive statements of my code. How can I get rid of the exception(in devices having less RAM). OR can reduce the time for which the code waits. Receiving status code of 200, clearly signifies that Server is done with its work, now all the handling must be performed on the client(Device) side.

Note : Already gone through all the three of the questions posted here on stackOverflow about the issue, but none of them was appropriate and was unable to solve the issue.

Why don't you try this one?

HttpGet get = new HttpGet(apiURL);
        HttpResponse response = client.execute(get);
        HttpEntity resEntity = response.getEntity();
        InputStream is = resEntity.getContent();
        String result = convertStreamToString(is);
public static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the
     * BufferedReader.readLine() method. We iterate until the BufferedReader
     * return null which means there's no more data to read. Each line will
     * appended to a StringBuilder and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

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

    return sb.toString();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM