2016-07-26 22 views
5

Folgen ist mein Android-Code zum Herunterladen von Datei von Server.HttpURLConnection Anfrage wird zweimal auf den Server zum Herunterladen von Datei

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; 
    } 

Ich habe diesen Code debugged. Diese Funktion wird nur einmal aufgerufen, auch wenn sie den Server zweimal trifft. Ist ihr irgendein Fehler in diesem Code.

Dank

+0

Versuch, um herauszufinden, welche Anfragen an den Server ankommen. Ich vermute, dass eine Anforderung für den Dateidownload besteht, die andere könnte das "Favicon" oder ein anderes nicht verwandtes Material anfordern. – f1sh

+0

Beide Anfragen sind gleich. –

+0

@RahulGiradkar Ich habe Antwort hinzugefügt, überprüfen Sie bitte –

Antwort

5

Ihr Fehler in dieser Linie liegt:

url.openStream() 

Wenn wir gehen zu den Quellen dieser Funktion grepcode, sehen wir dann:

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

Aber Sie bereits geöffnet Verbindung, so dass Sie die Verbindung zweimal öffnen.

Als Lösung benötigen Sie url.openStream() mit ersetzen connection.getInputStream()

So kann Ihr snipped Willen wie folgt aussieht:

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

Danke für den Vorschlag. Jetzt funktioniert es gut –