Android的URL连接getContentLength()返回负值 [英] android url connection getContentLength() returning negative value

查看:854
本文介绍了Android的URL连接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 doc的看着这一点,长度为负的原因主要有以下原因:

I looked at this in java doc, the length is negative because 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

此外,这是我想随着这个问题提到的其他三个下载图像第四种方法。

Also , This is the fourth method that i am trying to download images along with the other three mentioned in this question.

安卓大错误,同时下载图片

没有得到的答案依然。

编辑:我使用的方法的完整的code是如下

The complete code of the method that i am using is as below

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;

}

推荐答案

简单的回答是,内容长度是未知的。或者更具体地,服务器未设置内容长度头在响应消息

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.

您将不得不改变你的code,使其不会preallocate一个固定大小的字节数组保存图像。

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.

您现有的code在另一个方面,以及打破。如果你得到一个IOException或其他异常,code座将非正常退出不关闭的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 /最终确保的URLConnections,插座,溪流等的牵制外部资源始终是关闭的最佳实践。

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.

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

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