-2
HttpResponse response = client.execute(get, localContext);
HttpEntity entity = response.getEntity();
HttpEntity entity = response.getEntity();
long totalLength = entity.getContentLength();

why the totalLength is -1? I am sure the content is not null;

1 Answers1

1

That's because the content length is not known, as the docs mention.

Tells the length of the content, if known.

Returns:
the number of bytes of the content, or a negative number if unknown. If the content length is known but exceeds Long.MAX_VALUE, a negative number is returned.

When is the Content-Length header missing?
The HTTP specifications does allow the Content-Length to be missing if, for example, the Transfer-Encoding field is set. That is another way to check the length of the message.

How to show the download progress?
You should keep in mind that you cannot always determine the content length beforehand.
One thing you can do, is showing an indeterminate progress bar, like this:

Image with indeterminate progress

It shows the user the progress, but indicates that the progress value is indeterminate.

How to do so, see this question and answer.

Community
  • 1
  • 1
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
  • understand, But if I want to update the download progress, what should I do? – gdestiny Mar 25 '15 at 01:19
  • I believe that the server does not included the content length header. and it can be done on the server. Is that right @MCEmperor? – hasan Mar 25 '15 at 07:44
  • @gdestiny That's correct. The server does not always include the `Content-Length` header. – MC Emperor Mar 25 '15 at 07:46