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

lat*_*ata 6 java urlconnection progress

我想通过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;
}
Run Code Online (Sandbox Code Playgroud)

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

BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "ISO-8859-2"));
Run Code Online (Sandbox Code Playgroud)

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

Bal*_*usC 11

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

int contentLength = connection.getContentLength();

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

更新按照您的更新,你的包裹InputStreamBufferedReader,并阅读里面while循环.您可以按如下方式计算字节数:

int readBytes = 0;

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

+ 2是为了覆盖被吃掉的CRLF(回车和换行)字节BufferedReader#readLine().更简洁的方法是只读它,InputStream#read(buffer)这样你就不需要按字符前后按字节来计算读字节数.

也可以看看:

  • 嗯,你怎么读字节呢?我希望你只是在`for`或`while`循环中读取`connection.getInputStream()`.您只需计算此循环内的读取字节数.小学数学等. (2认同)