【问题标题】:Is it possible to check progress of URLconnection.getInputStream()?是否可以检查 URLconnection.getInputStream() 的进度?
【发布时间】:2011-03-01 23:06:20
【问题描述】:

我想通过 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;
}

我知道整个文件是在这一行下载的(或穿的)?:

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

那么可以在这段代码中做到这一点吗?

【问题讨论】:

标签: java progress urlconnection


【解决方案1】:

只需检查响应中是否存在 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) 读取它,这样您就不需要从字符来回按摩字节来计算读取的字节。

另见:

【讨论】:

  • 嗯,那么你是如何读取字节的呢?我希望您只是在for 或while 循环中阅读connection.getInputStream()。您只需计算此循环内的读取字节数。小学数学等等。
  • 当我将文件上传到服务器时,您知道如何制作相同但使用HttpURLConnection 吗?谢谢!
【解决方案2】:

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

【讨论】:

    【解决方案3】:
        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"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-11
      • 2011-11-29
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-03
      • 1970-01-01
      相关资源
      最近更新 更多