我有一个HTTP Request Dispatcher类,它在大多数时间都可以工作,但我注意到它在接收更大的请求时会“停顿”。在调查问题之后,我想也许我没有为缓冲区分配足够的字节。之前,我在做:
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();
我这样做了吗?无论如何,我可以根据请求的大小动态设置缓冲区的字节数吗?
...谢谢
答案 0 :(得分:3)
如果您愿意使用外部库,Apache IOUtils库会有一个toByteArray,它会将输入流转换为字节数组而无需您做任何工作。
这很简单:
byte[] buffer = IOUtils.toByteArray(connection.openInputStream());
答案 1 :(得分: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)的缓冲区通常绰绰有余。