我有一个简单的函数,用于连接到服务器并以字符串形式返回响应。当返回的数据量很小,但响应量很大时,它工作得很好。它不会完全存储服务器返回的响应字符串,并以...结尾。令人惊讶的是,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();
}发布于 2012-04-11 19:28:38
您是否获得了被截断的字符串(以...结尾)当你调试的时候?在返回之前尝试System.out.println(sb.toString());。
发布于 2012-04-11 19:00:58
(编辑:此答案基于OP最初发布的代码。此后,OP已对该问题进行了编辑,以更改违规代码。)
这里有一个bug:
sb.append(line.trim(), 0, line.length());如果line有任何前导空格或尾随空格,则line.length()将大于line.trim().length()。在本例中为sb.append() would throw IndexOutOfBoundsException
IndexOutOfBoundsException-如果start或end为负,或者start大于end,或者s.length()
大于
https://stackoverflow.com/questions/10104554
复制相似问题