决定从 InputStream 读取的字节数的因素

Factors deciding the number of bytes read from the InputStream

从urlConnection.getInputStream()获得的InputStream向ByteArrayOutputStream写入数据的处理耗时超过1分钟。

代码 片段

URL requestUrl= new URL(_sampleurl_);  
HttpURLConnection urlConnection=(HttpURLConnection)requestUrl.openConnection();  
urlConnection.setConnectTimeout(10000);  
urlConnection.setReadTimeout(10000);  
urlConnection.setRequestMethod("GET");  
urlConnection.connect();  
int statusCode=urlConnection.getResponseCode();   //200  
long contentLengthByTen = urlConnection.getHeaderFieldLong("Content-Length", _defaultSize_); //7631029  
InputStream inputStream = urlConnection.getInputStream();  
final byte[] byteArray = new byte[16384];  
int length;  
ByteArrayOutputStream byteArrOutStrm = new ByteArrayOutputStream();  
int k = 0;  
while ((length = inputStream.read(byteArray)) != -1)  
{  
    byteArrOutStrm.write(byteArray, 0, length);  
    k++;  
} 

一些观察结果是:
while循环单独执行一分钟多,迭代2650次左右
HttpURLConnection 响应代码为 200,因此整个内容在 InputStream 中可用。
该文件的内容长度为 7631029(字节)。

我有两个问题:

  1. 虽然字节数组大小为16384,状态码为200,但inputStream.read方法平均只读取2800字节。为什么以及哪些因素决定了这些字节?
  2. 减少处理时间的正确解决方案?
  1. Though the byte array size is 16384 and the status code is 200, the inputStream.read method reads only 2800 bytes averagely. Why and which factors decide these bytes?

套接字接收缓冲区中可用的字节数,它又是发送方速度、接收方读取频率、网络带宽和路径 MTU 的函数。您所看到的并不奇怪:这表明您与发件人的联系非常紧密。

  1. Proper solution to reduce the processing time?

让发件人发送更快。您的接收代码没有任何问题,但我想知道为什么您在对它进行任何操作之前将整个响应收集在 ByteArrayOutputStream 中。这只会浪费内存并增加延迟。