gpt4 book ai didi

java - StringBuffer 未完全读取

转载 作者:行者123 更新时间:2023-12-02 07:52:11 27 4
gpt4 key购买 nike

我有一个简单的函数,用于连接到服务器并将响应作为字符串返回。当返回的数据量较小但响应较大时,它可以正常工作。它不会完整存储服务器返回的响应字符串,并以...结尾。令人惊讶的是,system.out.println 返回了正确的响应。请帮帮我。我真的被困住了。

protected String getResponseFromServer(String URLaddress) {

HttpURLConnection connection = null;
URL serverAddress = null;
BufferedReader rd = null;
StringBuffer sb = new StringBuffer();
try {
serverAddress = new URL(URLaddress);
// set up out communications stuff
connection = null;
connection = (HttpURLConnection) serverAddress.openConnection();
connection.setReadTimeout(20000);
connection.connect();
// read the result from the server
rd = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.print(line.trim());
sb.append(line.trim());
}

} catch (Exception e) {
e.printStackTrace();
} finally {
// close the connection, set all objects to null
connection.disconnect();
connection = null;
}
return sb.toString();
}

最佳答案

(编辑:此答案基于 OP 最初发布的代码。该问题已由 OP 编辑​​以更改有问题的代码。)

这里有一个错误:

sb.append(line.trim(), 0, line.length());

如果line有任何前导或尾随空格,line.length()将大于line.trim().length()。在这种情况下sb.append() would throw IndexOutOfBoundsException :

IndexOutOfBoundsException - if start or end are negative, or start is greater than end or end is greater than s.length()

关于java - StringBuffer 未完全读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10104554/

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