Android - Header content-length equal -1 - android

I'm downloading a file in my android app and I want to display a progressbar. I need to know the total file size by using this method : here.
The problem is that I always get -1 despite the fact that it's set on the server and I can see it from my computer.
This is the code :
URL url = new URL(fileUrl);
URLConnection ucon = url.openConnection();
ucon.connect();
int length = ucon.getContentLength();
What is the problem ?

This is not related to Android, most probably it was not sent from the server..please use any sniffing tool to make sure the content length header is there.

Related

Android HttpURLConnection content length

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.
Set Accept-Encoding header to identity
Fetching the content length as string (from header field Content-Length) and then converting it to long
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);
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
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.

Value too large for defined data type Android

I am getting a java.io.IOException: Value too large for defined data type when uploading a large file almost 2.1GB to a server. and My code is :
URL oUrl = new URL(servierUrl);
HttpURLConnection connection = (HttpURLConnection) oUrl.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form- data");
connection.setRequestProperty("Content-Length", String.valueOf(nChunkSize));
connection.setConnectTimeout(1800000);
InputStream oFileInputStream = new FileInputStream(new File(sFilePath));
OutputStream outputStream = new DataOutputStream(connection.getOutputStream());
.
.
. // here I'm dividing the stream chunks, every chunk 5Mb and uploading the chuck to server
but in the chunk #410 (5Mb * 410) it cause an exception return the exception as I mentioned above.
before that every chunk I upload it success
.
.
So any help please.
My guess- something is using an int to hold the length of the file. This is overflowing at 2^31-1, or about 2 billion bytes. Looks like an issue in either the http library or the output stream. You're going to need to either break up that file or replace the breaking component by one that works. Which component is breaking can be found by looking higher up in the stack trace and seeing where the crash comes from.

Get Video size in MB Android

I want to get the video size in Mega Bytes from a Url in an android app. I have a Player that plays a video inside an app. I want to display next to my player the current videos size. So an example would me 23mb. If the video is 23 mg than I would have text next to the video that says 23mb. I tried looking through all the android mp.get functions but could not find what Iam looking for. Please help. Maybe I missed a function in Android. Or mayber there is anouther way to accomplush this. Thanks.
The value of the HTTP content-length header will provide the size of the file being downloaded.
Take a look at URLConnection.getHeaderField(String key) or HttpMessage.getFirstHeader(String name) depending on your server access code.
Try this will work in case the http server is giving the file size
URL myUrl = new URL("http://your_url.com/file.mp3");
URLConnection urlConnection = myUrl.openConnection();
urlConnection.connect();
int file_size = urlConnection.getContentLength();
file_size = file_size /1024;
Or second Version try this.
URL myUrl = new URL("http://your_url.com/file.mp3");
myConnection = myUrl.openConnection();
List headersize = myConnection.getHeaderFields().get("content-Lenght");

Posting a large file in Android

I sometimes get an OutOfMemoryError when posting a large file in Android. This is the code I'm using. Am I doing something wrong?
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
ostream = new DataOutputStream(con.getOutputStream());
byte[] buffer = new byte[1536];
int count;
while ((count = fileInput.read(buffer)) != -1) {
ostream.write(buffer, 0, count); // This sometimes causes OutOfMemoryError
}
ostream.flush();
Would calling ostream.flush() inside the while loop do any good?
If you do it like that, the whole POST must be buffered in memory. This is because it needs to send the Content-Length header first.
Instead, I think you want to use the Apache HTTP libraries, including FileEntity. That will let it figure out the length before reading the file. You can use this answer as a starting point. But the second parameter to the FileEntity constructor should be a mime type (like image/png, text/html, etc.).
HTTP connection is fine, but HTTPS will trigger Out of Memory error because there is a bug in HttpsURLConnectionImpl.java in Android 2.3.4 (verified on my tablet), and it's fixed in Android 4.1 (I have checked the source code).
By the way, he should avoid buffering the whole POST data in RAM by adding "con.setChunkedStreamingMode(0);" immediately after "con.setDoOutput(true);" statement.

getting the file size before downloading in android

Can anybody tell me how to get the size of a file before downloading it from server(may be http,ftp or anything) in android?.Does streaming works?. Please Help me..
Regards
Varnesh
Try this will work in case the http server is giving the file size
URL myUrl = new URL("http://jamants.com/file.mp3");
URLConnection urlConnection = myUrl.openConnection();
urlConnection.connect();
int file_size = urlConnection.getContentLength();
Or second Version try this.
URL myUrl = new URL("http://jamants.com/file.mp3");
myConnection = myUrl.openConnection();
List headersize = myConnection.getHeaderFields().get("content-Lenght");
It Works in my project.
If you are using the built-in Apahce HTTP library to make a request for a file, you can get the file size by requesting the headers only. Inside the headers will be a "content-length" attribute that will indicate the number of bytes of the requested file. Requesting the headers will not request the file itself.

Categories

Resources