URLConnection.getContentLength () returns -1

I have a URL that when I enter the browser opens the image perfectly. But when I try to execute 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 tell me what could be causing this?

+6
source share
1 answer

If the server sends a response using Chunked Transfer Encoding , you cannot pre-calculate the size. The response is streamed, and you just need to allocate a buffer to hold the image until the stream is complete. Please note that you should only do this if you can guarantee that the image is small enough to fit in memory. A flash stream response is a pretty reasonable option if the image can be large.

Solution in memory:

 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 is HTTP 1.0, most servers will return to non-streaming mode, but I don't think this is an option for URLConnection.

+8
source

Source: https://habr.com/ru/post/914850/


All Articles