Question

When opening a URLConnection I use the following code in order to get the content length, however it returns -1.

URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();

I presumed then that the server was not setting a content-length header (and a dig in the connection object confirms the value is -1), and so set one myself using the following in PHP:

header('Content-Length: '.strlen($output));

When I print out the value of strlen($output) I get the correct value, but this header does not seem to make it to Java.

Any suggestions or further code required? Thanks

Was it helpful?

Solution 2

Turns out content-length should be ignored when transfer-encoding is set to chunked. It would appear that my web host, takes this one further and strips out the header completely even if I set it manually in PHP. Confirmed with Chrome's advanced REST app.

OTHER TIPS

If the content length header is indeed being sent back to you from the server you are connecting to, then the code you have will work. You can prove that by hitting a simple web service that does return Content-Length like in the following code:

URL url = new URL("http://freegeoip.net/json/199.201.1.200");
URLConnection connection = url.openConnection();
int fileLength = connection.getContentLength();    
System.out.println(fileLength);

When you run this, you will see it print out a content length.

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