我有一个简单的函数用于连接服务器并将响应作为字符串返回。当返回的数据量很小但响应很大时,它可以正常工作。它不会完全存储服务器返回的响应字符串,并以...结束字符串。令人惊讶的是,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();
}