HttpURLConnection请求被命中两次到服务器下载文件

时间:2016-07-26 06:58:16

标签: java android httpurlconnection

以下是我从安装服务器下载文件的android代码。

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

我已调试此代码。即使它击中服务器两次,该函数也只被调用一次。 他们在这段代码中有任何错误。

谢谢

1 个答案:

答案 0 :(得分:8)

您的错误在于此行:

url.openStream()

如果我们将grepcode转到此函数的来源,那么我们将看到:

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

但是你已经打开了连接,所以你打开连接两次。

作为解决方案,您需要将url.openStream()替换为connection.getInputStream()

因此你的剪辑看起来像:

    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());