2012-06-11 78 views
1

我有一個從URL下載文件的方法。我需要編寫單元測試用例來恢復下載,那麼是否有任何方法來禁用/啓用網絡連接,以便恢復下載方法可以調用?停止/啓動網絡連接

我的下載方法如下:

public String download(LatestVersionInfo info) throws FileNotFoundException, XMLStreamException,NoSuchAlgorithmException, MalformedURLException {  
     boolean isCached = checkCache(info, location); 
     String filePath = null; 
     RandomAccessFile randomAccessFile = null; 
     InputStream inputStream = null; 
     if (!isCached) { 
      try { 
       createLocation(); 
       int responseCode = 0; 
       HttpsURLConnection connection = getSSLCertificate(info 
         .getLatestVersionUrl().toString()); 
       connection.setRequestMethod("GET"); 
       connection.setRequestProperty("Range", "bytes=" + downloaded 
         + "-"); 
       connection.connect(); 
       responseCode = connection.getResponseCode(); 
       if (responseCode/100 != 2) { 
        error(); 
       } 
       int contentLength = connection.getContentLength(); 
       if (contentLength < 1) { 
        error(); 
       } 
       if (size == -1) { 
        size = contentLength; 
        stateChanged(); 
       } 
       randomAccessFile = new RandomAccessFile(
         getDownLoadPath(info.getLatestVersionUrl()), "rw"); 
       randomAccessFile.seek(downloaded); 
       inputStream = connection.getInputStream(); 
       while (status == DOWNLOADING) { 
        byte buffer[]; 
        float finalSize = size - downloaded; 
        if (finalSize > MAX_BUFFER_SIZE) { 
         buffer = new byte[(int) finalSize]; 
        } else { 
         buffer = new byte[MAX_BUFFER_SIZE]; 
        } 
        int read = inputStream.read(buffer); 
        if (read == -1) 
         break; 

        randomAccessFile.write(buffer, 0, read); 
        downloaded += read; 
        stateChanged(); 
       } 

       if (status == DOWNLOADING) { 
        status = COMPLETE; 
        stateChanged(); 
       } 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } finally { 
       try { 
        if (randomAccessFile != null) 
         randomAccessFile.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
       try { 
        if (inputStream != null) 
         inputStream.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 

      }   
     } 
     return filePath; 
    } 

有什麼辦法禁用/啓用網絡連接使恢復下載的方法可以調用。

謝謝。

+0

'可以調用'什麼?這裏有什麼問題? – EJP

回答

1

看起來像是在連接失敗後試圖恢復,而不是以某種方式暫停底層TCP傳輸(這會更困難)。

所以你可以殺死HttpsURLConnection中途(從一個單獨的線程)。如果您將HttpsURLConnection connection置於一個字段中,另一個線程可能會調用connection.getInputStream().close(),這會導致連接「失敗」。