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) {
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.
source share