2010-04-16 64 views
3

我有一個HTTP請求調度程序類,大多數情況下都能正常工作,但我注意到它在收到更大的請求時「停止」。在研究這個問題後,我想我可能沒有爲緩衝區分配足夠的字節。之前,我是這樣做的:Java HTTP請求緩衝區大小

byte[] buffer = new byte[10000]; 

將其更改爲20000後,它似乎已經停止拖延:

String contentType = connection.getHeaderField("Content-type"); 
      ByteArrayOutputStream baos = new ByteArrayOutputStream(); 

      InputStream responseData = connection.openInputStream(); 
      byte[] buffer = new byte[20000]; 
      int bytesRead = responseData.read(buffer); 
      while (bytesRead > 0) { 
       baos.write(buffer, 0, bytesRead); 
       bytesRead = responseData.read(buffer); 
      } 
      baos.close(); 
      connection.close(); 

我這樣做對嗎?無論如何,我可以根據請求的大小動態設置緩衝區的字節數?

謝謝...

回答

1

這是從輸入流輸出的錯誤的方式。正確的做法是:

byte[] buffer = new byte[10000]; 
int bytesRead = 0; 
while ((bytesRead = responseData.read(buffer)) > 0) { 
    baos.write(buffer, 0, bytesRead); 
} 

byte[] buffer = new byte[10000]; 
for (int bytesRead = 0; (bytesRead = responseData.read(buffer)) > 0;) { 
    baos.write(buffer, 0, bytesRead); 
} 

另見Sun tutorial on the subject

1〜2K(1024〜2048)的緩衝區往往綽綽有餘。

+0

感謝您的建議! – littleK 2010-04-16 13:52:58

+0

不客氣。 – BalusC 2010-04-16 13:55:35

3

如果你打開使用外部庫,該庫Apache IOUtilstoByteArray,將輸入流轉換爲字節數組,而不需要您做任何工作。

很簡單:

byte[] buffer = IOUtils.toByteArray(connection.openInputStream()); 
+0

不幸的是,我正在研究一個對外部庫不提供很好支持的平臺。不過,我感謝你的幫助! – littleK 2010-04-16 13:52:40