Java:如何正确下载分块内容?

2024-01-08

我必须下载 HTTP 响应为“传输编码:分块”的文件,因为我无法“getContentLength”为 DataInputStream 分配新的字节缓冲区。 你能建议我如何正确地做吗?

代码示例非常简单:



try
{
       dCon = (HttpURLConnection) new URL(torrentFileDownloadLink.absUrl("href")).openConnection();
       dCon.setRequestProperty("Cookie", "session=" + cookies.get("session"));
       dCon.setInstanceFollowRedirects(false);
       dCon.setRequestMethod("GET");
       dCon.setConnectTimeout(120000);
       dCon.setReadTimeout(120000);  

      // byte[] downloadedFile == ???

      DataInputStream br = new DataInputStream((dCon.getInputStream()));
      br.readFully(downloadedFile);
      System.out.println(downloadedFile);

} 捕获(IOException 前) { Logger.getLogger(WhatCDWork.class.getName()).log(Level.SEVERE, null, ex); }


The HttpURLConnection将为您处理所有的去块工作。只需复制字节直到流结束:

byte[] buffer = new  byte[8192];
int count;
while ((count = in.read( buffer)) > 0)
{
    out.write(buffer, 0, count);
}
out.close();
in.close();

where out是无论什么OutputStream您想要将数据保存到。甚至可能是一个ByteArrayOutputStream如果你确实需要它在内存中,尽管这并不可取,因为并非所有内容都适合内存。

NB GET已经是默认的请求方法。你不必设置它。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java:如何正确下载分块内容? 的相关文章

随机推荐