相关疑难解决方法(0)

Android:将Stream转换为String而不会耗尽内存

我有一个Android客户端,通过REST-ful端点和JSON与服务器通信.因此,我需要在将其转换为Hash之前检索完整的服务器响应.我有这个代码(在互联网上找到的地方):

private 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) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
Run Code Online (Sandbox Code Playgroud)

代码在大多数情况下都有效,但是我看到来自具有OutOfMemory异常的客户端在该字段中崩溃的报告:

    while ((line = reader.readLine()) != null) {
Run Code Online (Sandbox Code Playgroud)

完整的堆栈跟踪是:

java.lang.RuntimeException: An error occured while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:200)
    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:124) …
Run Code Online (Sandbox Code Playgroud)

java android json out-of-memory

12
推荐指数
1
解决办法
2万
查看次数

标签 统计

android ×1

java ×1

json ×1

out-of-memory ×1