我有一个URL,当我在浏览器中输入该URL时,它会完美地打开图像。但是,当我尝试以下代码时,我将getContentLength()设为-1:
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// determine the image size and allocate a buffer
int fileSize = connection.getContentLength();
请指导我,这可能是什么原因?
最佳答案
如果服务器使用Chunked Transfer Encoding发送响应,则您将无法预先计算大小。响应是流式的,您只需要分配一个缓冲区来存储图像,直到流完成为止。请注意,只有在可以保证图像足够小以适合内存时,才应执行此操作。如果图像很大,则将响应流式传输到闪存是一个非常合理的选择。
内存中解决方案:
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
从理论上讲,如果Http客户端将其自身表示为HTTP 1.0,则大多数服务器将切换回非流式传输模式,但是我不认为URLConnection有这种可能性。