我必须下载哪个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);
}
catch(IOException ex)
{
Logger.getLogger(WhatCDWork.class.getName()).log(Level.SEVERE, null, ex);
}
1 回答
HttpURLConnection
将为您处理所有的去块 . 只需复制字节直到流结束:其中
out
是您想要保存数据的OutputStream
. 甚至可能是ByteArrayOutputStream
如果你真的需要它在内存中,虽然这是不可取的,因为并非一切都适合内存 .NB
GET
已经是默认的请求方法 . 您不必设置它 .