Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

android - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...