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); }
The
HttpURLConnectionwill take care of all the de-chunking for you. Just copy the bytes until end of stream:where
outis whateverOutputStreamyou want to save the data to. Could even be aByteArrayOutputStreamif you really need it in memory, although this isn't advisable as not everything fits into memory.NB
GETis already the default request method. You don't have to set it.