2013-07-25 45 views
1

我一直在試圖通過網絡服務下載一些文件,並將其完美下載,但現在我試圖添加一個功能,如果該文件沒有完全下載,應用程序應該下載僅剩下的字節數組,並追加到現有的一個,使用下載部分數據(黑莓)

connection = (HttpConnection) cf.getConnection(_url).getConnection(); 
int alreadyDownloaded = 0; 

if(connection.getResponseCode() == HttpConnection.HTTP_OK) { 
     inputStream = new DataInputStream(connection.openInputStream()); 
     final int len = (int) connection.getLength(); 
     if (len > 0) { 
     String filename = _url.substring(_url.lastIndexOf('/') + 1); 
     FileConnection outputFile = (FileConnection) Connector.open(path + filename, Connector.READ_WRITE, true); 

     if (!outputFile.exists()) { 
      outputFile.create(); 
     } else { 
      alreadyDownloaded = (int) outputFile.fileSize(); 
      connection.setRequestProperty("Range", "bytes=" + alreadyDownloaded + "-"); 
     } 

並且在該行

connection.setRequestProperty("Range", "bytes=" + alreadyDownloaded + "-"); 

我得到那個說

0123個例外

流不處於設置狀態

我該如何擺脫這個錯誤?

回答

2

的問題是,你在呼喚這一行

connection.setRequestProperty("Range", "bytes=" + alreadyDownloaded + "-"); 

後,你已經打開的連接,併發送請求參數。所以,現在改變Range屬性已經太晚了。

BlackBerry API docs:輸出流已經由openOutputStream或 openDataOutputStream方法打開

後,試圖改變請求經由setRequestMethod或調用setRequestProperty 參數被忽略。 一旦發送了請求參數,這些方法將拋出 一個IOException。

如果進一步往下看該文件中,他們表現出的例子,這也解釋多一點:

 // Getting the response code will open the connection, 
     // send the request, and read the HTTP response headers. 
     // The headers are stored until requested. 
     rc = c.getResponseCode(); 

所以,你只需要調用setRequestProperty()之前這一行:

if(connection.getResponseCode() == HttpConnection.HTTP_OK) { 
+0

謝謝奈特,它的工作! – Khawar