是否可以检查URLconnection.getInputStream()的进度? [英] Is it possible to check progress of URLconnection.getInputStream()?
问题描述
我想通过URLconnection检查下载文件的进度。是否可以或应该使用其他库?这是我的urlconnection函数:
I want to check progress of downloading file by URLconnection. Is it possible or should I use another library? This is my urlconnection function:
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)下载的?:
I understand that whole file is downloaded in this line (or worng)?:
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "ISO-8859-2"));
那么可以在此代码中执行此操作吗?
So is it possible to do this in this code?
推荐答案
只需检查响应中是否存在HTTP Content-Length
标头。
Just check if the HTTP Content-Length
header is present in the response.
int contentLength = connection.getContentLength();
if (contentLength != -1) {
// Just do (readBytes / contentLength) * 100 to calculate the percentage.
} else {
// You're lost. Show "Progress: unknown"
}
更新根据您的更新,您在 BufferedReader
中包装 InputStream
并且在循环中读取
。您可以按如下方式计算字节数:
Update as per your update, you're wrapping the InputStream
inside a BufferedReader
and reading inside a while
loop. You can count the bytes as follows:
int readBytes = 0;
while ((line = rd.readLine()) != null) {
readBytes += line.getBytes("ISO-8859-2").length + 2; // CRLF bytes!!
// Do something with line.
}
+ 2
是覆盖CRLF(回车和换行)字节,由 BufferedReader#readLine()
吃掉。更简洁的方法是通过 InputStream #read(buffer)
读取它,这样你就不需要按字符向前和向后按字节来计算读取的字节数。
The + 2
is to cover the CRLF (carriage return and linefeed) bytes which are eaten by BufferedReader#readLine()
. More clean approach would be to just read it by InputStream#read(buffer)
so that you don't need to massage the bytes forth and back from characters to calculate the read bytes.
- How to use
java.net.URLConnection
to fire and handle HTTP requests?
这篇关于是否可以检查URLconnection.getInputStream()的进度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!