2012-04-11 105 views
0

我有一個簡單的函數用於連接到服務器並將響應作爲字符串返回。當返回的數據量很小但響應很大時,它工作正常。它不會完全存儲服務器返回的響應字符串,並以...結束字符串... 令人驚訝的是,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(); 
} 
+4

你打印結果如何?它可能只是您的日誌框架截斷輸出。要確定,通過檢查返回的字符串的長度進行驗證。 – adarshr 2012-04-11 11:00:39

+0

'sb.append(line.trim(),0,line.length());'你最初(並且是基於我的答案)? – NPE 2012-04-11 11:04:19

+0

你介意如何打印它嗎?你產生太多好奇心。 – adarshr 2012-04-11 11:13:58

回答

0

您是否獲得該截斷的字符串(結尾。 ..),而你調試?嘗試System.out.println(sb.toString());在你回來之前。

+0

是的,它顯示了System.out.println的完整文本... Dat是一個非常愚蠢的錯誤。但是我收到的數據是JSON字符串,它正在轉換爲JSONObject,它將引發異常爲無效的JSON ...謝謝..但現在它也有時會產生相同的問題.. – Sumit 2012-04-11 12:14:54

2

(編輯:這個答案是基於OP已經最初發布這個問題已經被由OP編輯以改變違規的代碼。)

一個錯誤是在這裏:

sb.append(line.trim(), 0, line.length()); 

如果line有任何開頭或結尾空格,line.length()會比line.trim().length()更大。在這種情況下sb.append() would throw IndexOutOfBoundsException

IndexOutOfBoundsException - 如果startend爲負,或start大於endend大於s.length()

+2

據我所見,OP只是調用'sb.append(line.trim())'。你在哪裏看到這個版本? – adarshr 2012-04-11 11:02:48

+0

@adarshr:在我發佈答案之後,通過查看這些代碼被編輯出來的問題。讓我問OP ... – NPE 2012-04-11 11:03:45

+0

是的,我後來編輯了代碼.. – Sumit 2012-04-11 11:09:08