2016-07-26 2 views
5

以下は、サーバーからファイルをダウンロードするための私のアンドロイドコードです。ファイルをダウンロードするためにHttpURLConnection要求がサーバーに2回送信されました

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

私はこのコードをデバッグしました。この関数は、サーバに2回ヒットしても1回だけ呼び出されます。 このコードに誤りがありますか。私たちは、この関数のソースにgrepcodeに行く場合は、私たちが表示されます

url.openStream() 

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

しかし、あなたはすでに開かれ

+0

。私は1つのリクエストがファイルのダウンロードであると思われますが、もう1つは '' favicon'やその他の関連しないものを要求するかもしれません。 – f1sh

+0

両方のリクエストは同じです。 –

+0

@RahulGiradkar私は答えを追加しました。それを確認してください。 –

答えて

5

あなたのエラーは、この行にある

感謝接続を開くので、接続を2回開きます。あなたは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

ありがとうございます。今それは正常に動作します –

関連する問題