Java:如何正确下载分块内容?
我必须下载 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
HttpURLConnection
将为您处理所有的分块操作。只需复制字节直到流结束:其中
out
是您想要将数据保存到的任何OutputStream
。如果您确实需要在内存中使用它,甚至可以是 ByteArrayOutputStream,尽管这并不可取,因为并非所有内容都适合内存。注意
GET
已经是默认的请求方法。你不必设置它。The
HttpURLConnection
will take care of all the de-chunking for you. Just copy the bytes until end of stream:where
out
is whateverOutputStream
you want to save the data to. Could even be aByteArrayOutputStream
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.