Question

I am trying to download files from a server in android and show progress dialog using code very similar to the answer provided in this thread but i am not able to get content length in HttpURLConnection's getContentLength() method. Content length for all files is -1.

For the same file, i get correct content length in iOS app with NSHTTPURLResponse's expectedContentLength method.

Is there some basic difference in the way these methods fetch the content length for an http connection/response?

EDIT 1:

Tried following few things as suggested some answers and comments.

  1. Set Accept-Encoding header to identity
  2. Fetching the content length as string (from header field Content-Length) and then converting it to long
  3. Tried conn.getContent().toString().length() instead of getContentLength()

None of these worked for me yet.

What baffles me most is i get the content length in iOS but not on android.

EDIT 2:

Heres my iOS and Android code for comparison -

iOS:

NSURLRequest *request = [NSURLRequest requestWithURL:self.url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1200.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[connection start];

Android:

URL url = new URL(downloadUrlString);
connection = (HttpURLConnection) url.openConnection();
connection .setRequestProperty("Accept-Encoding", "identity");
connection.connect();

The only difference i can see is caching. So i added following line in android code as well but nothing changed.

connection.setUseCaches(true);
Was it helpful?

Solution 3

Root cause for this problem turned out to be Cookies.

I am using a web view in one of the activities in my application. Some cookies are stored by the web view. All other REST api and file download requests work without those cookies however for a particular type of requests, the cookies are necessary.

Apparently, android web view and the connection requests do not share cookies out of the box like iOS. As a result i had to make changes in my code to make sure that the HttpUrlConnection uses WebKit's cookie store. I did it using method described in the accepted answer for this question.

OTHER TIPS

try this:

   HttpURLConnection conn = (HttpURLConnection)url.openConnection();
   conn .setRequestProperty("Accept-Encoding", "identity");
   conn.connect();

if you just need to content length, can you try

  conn.getContent().toString().length()

where conn is the HttpURLConnection object

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top