gpt4 book ai didi

java - 无法从输入流读取大量 JSON 数据

转载 作者:行者123 更新时间:2023-12-01 07:53:16 25 4
gpt4 key购买 nike

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 字节,那么一切都可以(因此上面的代码确实适用于较小的数据)。但我有一些大小约为 15000 字节 的 JSON,因此我将最大大小设置为 16092

但是,它只读取大约 6511 的 JSON,然后就被切断了。

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

我在这里做错了什么吗?我应该检查什么。

非常感谢您的建议,

最佳答案

尝试以下代码:

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;
}

关于java - 无法从输入流读取大量 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33778863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com