URLConnection.getContentLength retornando -1

Eu estou criando um programa que precia fazer o download de uns arquivos, eu estou usando URLConnection, eu queria colocar uma ProgressBar para o usuario monitorar a porcentagem e o tamanho do Download só que porem, quando dou, getContentLenght() ou getContentLengthLong() o valor retornado é sempre, -1, eu já tentei:

 URLConnection connecion = url.openConnection(); //Url: htttp://...
 connection.setRequestProperty( "Accept-Encoding" , "identity" );
 long length = connnection.getContentLength();

e tambem tentei:

 HttpURLConnection connecion = url.openConnection(); //Url: http://.....
 connection.setRequestMethod("HEAD");
 long length = connnection.getContentLength();

e tambem tentei os dois juntos só que o valor retornado sempre é -1.
Desde já agradeço quem puder ajudar.

Experimentou olhar a documentação do método?
https://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#getContentLength--

the content length of the resource that this connection’s URL references, -1 if the content length is not known, or if the content length is greater than Integer.MAX_VALUE.

Traduzindo: quando vem -1 é porque tamanho é desconhecido ou quando é maior do que cabe num int. O getContentLengthLong() volta -1 quando o tamanho é desconhecido.

1 curtida