我有一個簡單的函數用於連接到服務器並將響應作爲字符串返回。當返回的數據量很小但響應很大時,它工作正常。它不會完全存儲服務器返回的響應字符串,並以...結束字符串... 令人驚訝的是,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();
}
你打印結果如何?它可能只是您的日誌框架截斷輸出。要確定,通過檢查返回的字符串的長度進行驗證。 – 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