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

Rah*_*kar 5 java android httpurlconnection

以下是我从android下载文件的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;
    }
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Mic*_*sin 8

你的错误在于这一行:

url.openStream()
Run Code Online (Sandbox Code Playgroud)

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

public final InputStream openStream() throws java.io.IOException {
    return openConnection().getInputStream();
}
Run Code Online (Sandbox Code Playgroud)

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

作为解决方案,您需要更换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());
Run Code Online (Sandbox Code Playgroud)