我想通过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"));
那么可以在此代码中执行此操作吗?
答案 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"));