URLConnection getContentLength()返回负值 [英] URLConnection getContentLength() is returning a negative value

查看:207
本文介绍了URLConnection getContentLength()返回负值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

url = paths[0];
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int length = connection.getContentLength(); // i get negetive length
InputStream is = (InputStream) url.getContent();
byte[] imageData = new byte[length]; 
int buffersize = (int) Math.ceil(length / (double) 100);
int downloaded = 0;
int read;
while (downloaded < length) {
    if (length < buffersize) {
        read = is.read(imageData, downloaded, length);
    } else if ((length - downloaded) <= buffersize) {
        read = is.read(imageData, downloaded, length - downloaded);
    } else {
        read = is.read(imageData, downloaded, buffersize);
    }
    downloaded += read;
    publishProgress((downloaded * 100) / length);
}
Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0,
        length);
if (bitmap != null) {
    Log.i(TAG, "Bitmap created");
} else {
    Log.i(TAG, "Bitmap not created");
}
is.close();
return bitmap;

我在Java文档中查看了这个,由于以下原因,长度为负:

I looked at this in Java documentation and the length is negative because of the following reason:


内容的字节数,如果未知则为负数。如果内容>长度已知但超过Long.MAX_VALUE,则为负数号码被退回。

"the number of bytes of the content, or a negative number if unknown. If the content >length is known but exceeds Long.MAX_VALUE, a negative number is returned."

这可能是什么原因?我正在尝试下载图像。我想指出这是我尝试下载图像的第四种方法。其他三个提到这里

What might be the reason for this? I am trying to download an image. I would like to point out that this is the fourth method that I am trying to download images. The other three are mentioned here.

修改:

根据要求,这是我正在使用的完整方法。

As requested, here is the full method I am using.

protected Bitmap getImage(String imgurl) {

    try {
        URL url = new URL(imgurl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        int length = connection.getContentLength();
        InputStream is = (InputStream) url.getContent();
        byte[] imageData = new byte[length];
        int buffersize = (int) Math.ceil(length / (double) 100);
        int downloaded = 0;
        int read;
        while (downloaded < length) {
            if (length < buffersize) {
                read = is.read(imageData, downloaded, length);
            } else if ((length - downloaded) <= buffersize) {
                read = is.read(imageData, downloaded, length
                        - downloaded);
            } else {
                read = is.read(imageData, downloaded, buffersize);
            }
            downloaded += read;
        //  publishProgress((downloaded * 100) / length);
        }
        Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0,length);
        if (bitmap != null) {
             System.out.println("Bitmap created");
        } else {
            System.out.println("Bitmap not created");
        }
        is.close();
        return bitmap;
    } catch (MalformedURLException e) {
        System.out.println(e);
    } catch (IOException e) {
        System.out.println(e);
    } catch (Exception e) {
        System.out.println(e);
    }
    return null;
}


推荐答案

简单的答案是内容长度未知。或者更具体地说,服务器没有在响应消息中设置Content-Length标头。

The simple answer is that the content length is not known. Or more specifically, the server is not setting a "Content-Length" header in the response message.

您必须更改代码,以便它不会预先分配一个固定大小的字节数组来保存图像。

You will have to change your code so that it doesn't preallocate a fixed sized byte array to hold the image.


  • 另一种方法是创建一个本地 ByteArrayOutputStream 并复制字节读取从插座到那个。然后调用 toByteArray 来获取完整的字节数组。

  • One alternative is to create a local ByteArrayOutputStream and copy bytes read from the socket to that. Then call toByteArray to grab the full byte array.

如果你可以改变服务器端,另一个替代方法是在响应中设置内容长度标头。在获得OutputStream将图像字节写入响应之前,必须完成此操作。

If you can change the server side, another alternative is to set the content length header in the response. This has to be done BEFORE you get the OutputStream to write the image bytes to the response.

您现有的代码也在另一方面被打破。如果您收到IOException或其他异常,代码块将异常退出而不关闭URLConnection。这将导致文件描述符的泄漏。执行此操作太多次,并且您的应用程序将因文件描述符...或本地端口号耗尽而失败。

You existing code is broken in another respect as well. If you get an IOException or some other exception, the code block will "exit abnormally" without closing the URLConnection. This will result in the leakage of a file descriptor. Do this too many times and your application will fail due to exhaustion of file descriptors ... or local port numbers.

最佳做法是使用try / finally确保关闭外部资源的URLConnections,Sockets,Streams等始终关闭。

It is best practice to use a try / finally to ensure that URLConnections, Sockets, Streams and so on that tie down external resources are ALWAYS closed.

这篇关于URLConnection getContentLength()返回负值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆