来自 HttpURLConnection 的对象的 InputStream 未获取所有数据

InputStream for Objects from HttpURLConnection Not Getting All Data

所以我有一个 HttpURLConnection 连接到某些 URL 上的某些图像。我正在使用范围 属性 下载此图像(在单独的并行连接中下载一个文件)。在我抓住所有零件后,我将它们缝合在一起。一切都很好,除非我尝试使用更大的文件执行 InputStream(这意味着我可以在 200 个并行连接中获取一个文件,但不是 5 个)。

例如:

假设我想下载对象:http://stuorgs.uga.edu/images/spotlight/spotlight_button.png 只需 1 个部分。所以我的范围是从 bytes=0-max。我的程序创建了一个最大大小的字节数组,并将来自 HttpURLConnection 的 InputStream 读入该数组。但是,InputStream 在某个点之后,要么只发送超过 0000,要么过早关闭。

这是我的代码:

try {
    HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
    String bytesToGrab = "bytes=" + startingByte + "-" + endingByte;
    urlConnection.setRequestProperty("Range", bytesToGrab);

    int sizeOfData = endingByte - startingByte;
    byte[] storeData = new byte[sizeOfData];

    InputStream inputStream = urlConnection.getInputStream();
    inputStream.read(storeData);
    inputStream.close();

    createFile(storeData); // this takes the byte array and creates a file with it
} catch (IOException e) {
    System.out.println("Cannot open url connection: " + e);
} 

那么,我的 InputStream 是不是提早关闭了?如果是这样,我该如何防止这种情况发生?不然怎么了?

Javadoc 中没有任何地方声明 InputStreamread(byte[]) 填充了缓冲区。 它阻塞直到至少一个字节的数据可用,然后传输任何可用的数据,并且 returns 传输的字节数。

你必须循环。或者使用 DataInputStream.readFully().

注意不要在 类 之后命名变量,也不要以大写字母开头。那是 类.