HttpURLConnection请求被两次击中服务器以下载文件 [英] HttpURLConnection request being hit twice to the server for downloading file

查看:73
本文介绍了HttpURLConnection请求被两次击中服务器以下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的android代码,用于从服务器下载文件.

Following is my android code for downloading file from sever.

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 have debugged this code. This function is called only once even if it hits server twice. Is their any error in this code.

谢谢

推荐答案

您的错误在于此行:

url.openStream()

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

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

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

但是您已经打开了连接,因此您打开了两次连接.

But you already opened connection, so you opening connection twice.

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

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

因此,您的片段看起来像:

Thus your snipped will looks like:

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

这篇关于HttpURLConnection请求被两次击中服务器以下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆