2016-07-26 57 views
5

以下是我從服務器下載文件的android代碼。HttpURLConnection請求被擊中兩次到服務器上下載文件

private String executeMultipart_download(String uri, String filepath) 
      throws SocketTimeoutException, IOException { 
     int count; 
     System.setProperty("http.keepAlive", "false"); 
     // uri="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTzoeDGx78aM1InBnPLNb1209jyc2Ck0cRG9x113SalI9FsPiMXyrts4fdU"; 
     URL url = new URL(uri); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.connect(); 
     int lenghtOfFile = connection.getContentLength(); 
     Log.d("File Download", "Lenght of file: " + lenghtOfFile); 

     InputStream input = new BufferedInputStream(url.openStream()); 
     OutputStream output = new FileOutputStream(filepath); 
     byte data[] = new byte[1024]; 
     long total = 0; 

     while ((count = input.read(data)) != -1) { 
      total += count; 
      publishProgress("" + (int) ((total * 100)/lenghtOfFile)); 
      output.write(data, 0, count); 
     } 
     output.flush(); 
     output.close(); 
     input.close(); 
     httpStatus = connection.getResponseCode(); 
     String statusMessage = connection.getResponseMessage(); 
     connection.disconnect(); 
     return statusMessage; 
    } 

我已調試此代碼。即使該服務器訪問服務器兩次,該功能也只會被調用一次。 是他們在此代碼中的任何錯誤。

感謝

+0

嘗試找出哪些請求到達服務器。我懷疑一個請求是文件下載,另一個可能請求「favicon」或其他非相關的東西。 – f1sh

+0

兩個請求都一樣。 –

+0

@RahulGiradkar我已經添加了答案,請檢查它 –

回答

5

你的錯誤就出在這行:

url.openStream() 

如果我們去grepcode這個功能的來源,那麼我們將看到:

public final InputStream openStream() throws java.io.IOException { 
    return openConnection().getInputStream(); 
} 

但是你已經打開連接,所以你打開連接兩次。

至於解決方案,你需要connection.getInputStream()

因此,你會剪斷貌似更換url.openStream()

HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
    connection.connect(); 
    int lenghtOfFile = connection.getContentLength(); 
    Log.d("File Download", "Lenght of file: " + lenghtOfFile); 

    InputStream input = new BufferedInputStream(connection.getInputStream()); 
+0

感謝您的建議。現在它工作正常 –

相關問題