我必须下载 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);<p></p>
<pre><code> // byte[] downloadedFile == ???
DataInputStream br = new DataInputStream((dCon.getInputStream()));
br.readFully(downloadedFile);
System.out.println(downloadedFile);
</code></pre>
<p>}
catch(IOException ex)
{
Logger.getLogger(WhatCDWork.class.getName()).log(Level.SEVERE, null, ex);
}
</p>
最佳答案
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
已经是默认的请求方法。您不必设置它。
关于Java:如何正确下载分块内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5737945/