6

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

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

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

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

4

3 回答 3

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"
}

根据您的更新进行更新,您将包装InputStream内部 a并在循环中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是为了覆盖 CRLF(回车和换行)字节被BufferedReader#readLine(). 更干净的方法是只读取它,InputStream#read(buffer)这样您就不需要从字符来回按摩字节来计算读取的字节。

也可以看看:

于 2011-03-01T23:08:48.937 回答
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"));
于 2014-05-21T22:10:55.730 回答
0

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

于 2011-03-01T23:10:06.833 回答