【问题标题】:Can not read large JSON data from inputstream无法从输入流中读取大型 JSON 数据
【发布时间】:2015-11-18 11:27:56
【问题描述】:
Java(TM) SE Runtime Environment (build 1.7.0_45-b18)

你好,

我正在使用httpUrlConnection 从 Web 服务中检索 json 字符串。然后我从连接中得到inputStream

jsonString = readJSONInputStream(mHttpUrlconnection.getInputStream());

然后我使用以下函数读取输入流以获取 JSON。

private String readJSONInputStream(final InputStream inputStream) {
    log.log(Level.INFO, "readJSONInputStream()");

    Reader reader = null;

    try {
        final int SIZE = 16092;

        char[] buffer = new char[SIZE];
        int bytesRead = 0;
        int read = 0;

        reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), SIZE);
        bytesRead = reader.read(buffer);

        String jsonString = new String(buffer, 0, bytesRead);
        log.log(Level.INFO, "bytesRead: " + bytesRead + " [ " + jsonString + " ]");
        /* Success */
        return jsonString;
    }
    catch(IndexOutOfBoundsException ex) {
        log.log(Level.SEVERE, "UnsupportedEncodingexception: " + ex.getMessage());
    }
    catch(IOException ex) {
        log.log(Level.SEVERE, "IOException: " + ex.getMessage());
    }
    finally {
        /* close resources */
        try {
            reader.close();
            inputStream.close();
        }
        catch(IOException ex) {
            log.log(Level.SEVERE, "IOException: " + ex.getMessage());
        }
    }

    return null;
}

但是,如果 json 很小,比如600 bytes,那么一切正常(所以上面的代码确实适用于较小的数据)。但我有一些 JSON 大小约为 15000 bytes,因此我将最大大小设置为 16092

但是,它只读取大约 6511 的 JSON 并且只是切断了。

我不明白如果 JSON 很小就没有问题。但是对于较大的 JSON,它每次都会以相同的大小截断。

我在这里做错什么了吗?我应该检查的任何内容。

非常感谢您的任何建议,

【问题讨论】:

标签: java httpurlconnection


【解决方案1】:

试试下面的代码:

String readResponse(InputStream inputStream) throws IOException {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while ((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;
}

【讨论】:

  • 现在测试你的代码。您不应该在 while 循环中测试 -1 而不是 null 吗?
  • 它工作得很好,我已经多次使用相同的代码。给你添麻烦了吗??
  • 回报对我来说仍然被截断/剪切
【解决方案2】:

您的代码很可能在这里被破坏:

bytesRead = reader.read(buffer);

您应该循环阅读。我认为您没有从流中读取所有字符。

【讨论】:

    【解决方案3】:

    您应该继续从缓冲区读取,直到 bytesRead = -1。

    我怀疑阅读器正在缓冲数据,并且一次只返回一定数量的数据。

    尝试循环直到 bytesRead == -1,每个循环将读取的数据附加到结果字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-13
      • 1970-01-01
      • 2017-01-10
      • 2022-01-11
      • 1970-01-01
      • 2016-02-21
      • 1970-01-01
      相关资源
      最近更新 更多