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

发布于 2024-11-02 07:52:09 字数 849 浏览 5 评论 0原文

我必须下载 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); }

I have to download file which HTTP response is "Transfer-Encoding: Chunked", because of what I can't to «getContentLength» to allocate new bytes buffer for DataInputStream.
Can you advice me how to do it correctly?

Code example is very simple:

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);

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蝶…霜飞 2024-11-09 07:52:09

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

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

其中 out 是您想要将数据保存到的任何 OutputStream。如果您确实需要在内存中使用它,甚至可以是 ByteArrayOutputStream,尽管这并不可取,因为并非所有内容都适合内存。

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

The HttpURLConnection will take care of all the de-chunking for you. Just copy the bytes until end of stream:

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

where out is whatever OutputStream you want to save the data to. Could even be a ByteArrayOutputStream if you really need it in memory, although this isn't advisable as not everything fits into memory.

NB GET is already the default request method. You don't have to set it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文