有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

下面是我从服务器下载文件的安卓代码

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) 个答案

  1. # 1 楼答案

    您的错误在于这一行:

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