是否可以检查URLconnection.getInputStream()的进度?

时间:2011-03-01 23:06:20

标签: java progress urlconnection

我想通过URLconnection检查下载文件的进度。是否可以或应该使用其他库?这是我的urlconnection函数:

public static String sendPostRequest(String httpURL, String data) throws UnsupportedEncodingException, MalformedURLException, IOException {
    URL url = new URL(httpURL);

    URLConnection conn = url.openConnection();
    //conn.addRequestProperty("Content-Type", "text/html; charset=iso-8859-2");
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "ISO-8859-2"));
    String line, all = "";
    while ((line = rd.readLine()) != null) {
        all = all + line;
    }
    wr.close();
    rd.close();
    return all;
}

据我所知,整个文件都是在这行(或worng)中下载的?:

BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "ISO-8859-2"));

那么可以在此代码中执行此操作吗?

3 个答案:

答案 0 :(得分:11)

只需检查响应中是否存在HTTP Content-Length标头。

int contentLength = connection.getContentLength();

if (contentLength != -1) {
    // Just do (readBytes / contentLength) * 100 to calculate the percentage.
} else {
    // You're lost. Show "Progress: unknown"
}

更新根据您的更新,您将InputStream包裹在BufferedReader内并阅读while循环内部。您可以按如下方式计算字节数:

int readBytes = 0;

while ((line = rd.readLine()) != null) {
    readBytes += line.getBytes("ISO-8859-2").length + 2; // CRLF bytes!!
    // Do something with line.
}

+ 2将覆盖由BufferedReader#readLine()吃掉的CRLF(回车和换行)字节。更简洁的方法是只需通过InputStream#read(buffer)读取它,这样就不需要按字符向前和向后按字节来计算读取字节。

另见:

答案 1 :(得分:0)

将其包装在javax.swing.ProgressMonitorInputStream中。但请注意,Java可能会在开始将整个响应传递到流之前缓冲整个响应...

答案 2 :(得分:0)

    BufferedReader rd = new BufferedReader(new InputStreamReader(new FilterInputStream(conn.getInputStream())
    {
        public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException
        {
            int count = super.read(buffer, byteOffset, byteCount);
            // do whatever with count, i.e. mDownloaded += count;
            return count;
        }
    }, "ISO-8859-2"));