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

2024-01-12

我想通过 URL 连接检查下载文件的进度。是否可能或者我应该使用另一个库?这是我的 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"));

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


只需检查 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"
}

Update根据您的更新,您正在包装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.
}

The + 2是为了覆盖被吃掉的 CRLF(回车和换行)字节BufferedReader#readLine()。更干净的方法是直接阅读它InputStream#read(buffer)这样您就不需要从字符来回调整字节来计算读取的字节。

也可以看看:

  • 如何使用java.net.URLConnection触发并处理 HTTP 请求? https://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否可以检查 URLconnection.getInputStream() 的进度? 的相关文章