URLConnection.getContentLength()返回-1URLConnection、getContentLength

2023-09-12 10:32:55 作者:谈不起的一场恋爱゛

我有,当我在浏览器中输入,完全打开的图像的URL。但是,当我尝试以下code,我得到getContentLength()为-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?

推荐答案

如果服务器发送下使用块传输编码的响应< /一>,你将无法pre-计算大小。该响应流,你就只需要分配一个缓冲区来存储图像,直到流完成。请注意,您应该只有这样做,如果你能保证图像小到足以放入内存中。流应对闪存是pretty的合理选择,如果图像可能会很大。

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.

在内存解决方案:

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客户端presents本身作为HTTP 1.0,大多数服务器将切换回非流模式,但我不认为这是一种可能性的URLConnection。

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.