The HttpURLConnection request hits the server twice to download the file

Below is my Android code for downloading a file from the server.

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

I debugged this code. This function is called only once, even if it hits the server twice. This is their mistake in this code.

thanks

+5
source share
1 answer

Your error lies in this line:

 url.openStream() 

If we go to grepcode to the sources of this function, we will see:

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

But you have already opened the connection, so open the connection twice.

As a solution, you need to replace url.openStream() with connection.getInputStream()

So your cut off will look like this:

  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()); 
+5
source

All Articles