我有一个简单的函数,用于连接到服务器并将响应作为字符串返回。当返回的数据量较小但响应较大时,它可以正常工作。它不会完整存储服务器返回的响应字符串,并以...结尾。 令人惊讶的是,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
- ifstart
orend
are negative, orstart
is greater thanend
orend
is greater thans.length()
关于java - StringBuffer 未完全读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10104554/