StringBuffer没有完全读取
我有一个简单的函数用于连接到服务器并将响应作为字符串返回。当返回的数据量很小但响应很大时,它工作正常。它不会完全存储服务器返回的响应字符串,并以...结束字符串... 令人惊讶的是,system.out.println返回正确的响应。请帮助我。我很困难。StringBuffer没有完全读取
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();
}
您是否获得该截断的字符串(结尾。 ..),而你调试?尝试System.out.println(sb.toString());在你回来之前。
是的,它显示了System.out.println的完整文本... Dat是一个非常愚蠢的错误。但是我收到的数据是JSON字符串,它正在转换为JSONObject,它将引发异常为无效的JSON ...谢谢..但现在它也有时会产生相同的问题.. – Sumit 2012-04-11 12:14:54
(编辑:这个答案是基于OP已经最初发布这个问题已经被由OP编辑以改变违规的代码。)
一个错误是在这里:
sb.append(line.trim(), 0, line.length());
如果line
有任何开头或结尾空格,line.length()
会比line.trim().length()
更大。在这种情况下sb.append()
would throw IndexOutOfBoundsException
:
IndexOutOfBoundsException
- 如果start
或end
为负,或start
大于end
或end
大于s.length()
你打印结果如何?它可能只是您的日志框架截断输出。要确定,通过检查返回的字符串的长度进行验证。 – adarshr 2012-04-11 11:00:39
'sb.append(line.trim(),0,line.length());'你最初(并且是基于我的答案)? – NPE 2012-04-11 11:04:19
你介意如何打印它吗?你产生太多好奇心。 – adarshr 2012-04-11 11:13:58