簡體   English   中英

來自HttpURLConnection的對象的InputStream無法獲取所有數據

[英]InputStream for Objects from HttpURLConnection Not Getting All Data

所以我有一個HttpURLConnection連接到某些URL上的某些圖像。 我正在使用Range屬性下載此圖像(在單獨的並行連接中下載一個文件)。 抓住所有零件后,將它們縫在一起。 除非我嘗試對一個更大的文件進行InputStream,否則一切都會很好地工作(這意味着我可以通過200個並行連接獲取文件,但不能以5個並行連接獲取文件)。

例如:

假設我要下載對象: http : //stuorgs.uga.edu/images/spotlight/spotlight_button.png僅1部分。 所以我的范圍是從字節= 0-最大。 我的程序創建了一個最大大小為字節的字節數組,並將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[])填充了緩沖區。 它會阻塞,直到至少一個字節的數據可用,然后再傳輸所有可用數據,並返回已傳輸字節的計數。

你必須循環。 或使用DataInputStream.readFully()

注意:不要在課后命名變量,也不要以大寫字母開頭。 那是上課的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM