【问题标题】:Java: How to download chunked content correctly?Java:如何正确下载分块内容?
【发布时间】:2011-08-09 22:12:07
【问题描述】:

我必须下载 HTTP 响应为“Transfer-Encoding: Chunked”的文件,因为我无法通过 «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 ex) { Logger.getLogger(WhatCDWork.class.getName()).log(Level.SEVERE, null, ex); }

【问题讨论】:

    标签: java chunked-encoding chunked http-chunked


    【解决方案1】:

    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,尽管这不是可取的,因为并非所有东西都适合内存。

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

    【讨论】:

      猜你喜欢
      • 2012-08-27
      • 2012-04-17
      • 1970-01-01
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      • 2011-11-15
      • 2016-07-24
      • 1970-01-01
      相关资源
      最近更新 更多