Khawar
Khawar

Reputation: 5227

URLConnection.getContentLength() returns -1

I have a URL which, when I enter in browser, opens the image perfectly. But when I try the following code, I get getContentLength() as -1:

URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// determine the image size and allocate a buffer
int fileSize = connection.getContentLength();

Please guide me what can be the reason behind this?

Upvotes: 7

Views: 9406

Answers (2)

amit semwal
amit semwal

Reputation: 415

I am late here but this might help someone. I was facing same issue i was always getting -1 value, when ever i was trying get the content length.

previously i was using below method to get content length.

long totalByte=connection.getContentLength();

Below fixed my problem:-

long totalByte=connection.getHeaderFieldLong("Content-Length",-1);

Upvotes: 2

dagalpin
dagalpin

Reputation: 1307

If the server is sending down the response using Chunked Transfer Encoding, you will not be able to pre-calculate the size. The response is streamed, and you'll just have to allocate a buffer to store the image until the stream is complete. Note that you should only do this if you can guarantee that the image is small enough to fit into memory. Streaming the response to flash storage is a pretty reasonable option if the image may be large.

In-memory solution:

private static final int READ_SIZE = 16384;

byte[] imageBuf;
if (-1 == contentLength) {
    byte[] buf = new byte[READ_SIZE];
    int bufferLeft = buf.length;
    int offset = 0;
    int result = 0;
    outer: do {
        while (bufferLeft > 0) {
            result = is.read(buf, offset, bufferLeft);
            if (result < 0) {
                // we're done
                break outer;
            }
            offset += result;
            bufferLeft -= result;
         }
         // resize
         bufferLeft = READ_SIZE;
         int newSize = buf.length + READ_SIZE;
         byte[] newBuf = new byte[newSize];
         System.arraycopy(buf, 0, newBuf, 0, buf.length);
         buf = newBuf;
     } while (true);
     imageBuf = new byte[offset];
     System.arraycopy(buf, 0, imageBuf, 0, offset);
 } else { // download using the simple method

In theory, if the Http client presents itself as HTTP 1.0, most servers will switch back to non-streaming mode, but I don't believe this is a possibility for URLConnection.

Upvotes: 9

Related Questions