【问题标题】:URLConnection getContentLength() is returning a negative valueURLConnection getContentLength() 返回负值
【发布时间】:2011-07-22 16:01:07
【问题描述】:

这是我的代码:

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 文档中查看了这个,长度为负数,原因如下:

“内容的字节数,如果未知,则为负数。如果内容>长度已知但超过Long.MAX_VALUE,则返回负数。”

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

编辑:

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

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;
}

【问题讨论】:

    标签: java android httpurlconnection


    【解决方案1】:

    默认情况下,此 HttpURLConnection 实现请求服务器使用 gzip 压缩。
    由于 getContentLength() 返回传输的字节数,因此您无法使用该方法预测可以从 getInputStream() 读取多少字节。
    相反,读取该流直到它耗尽:当 read() 返回 -1。
    可以通过在请求标头中设置可接受的编码来禁用 Gzip 压缩:

     urlConnection.setRequestProperty("Accept-Encoding", "identity");
    

    所以试试这个:

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Accept-Encoding", "identity"); // <--- Add this line
    int length = connection.getContentLength(); // i get negetive length
    

    来源(表演段落):http://developer.android.com/reference/java/net/HttpURLConnection.html

    【讨论】:

    • 谢谢,这是完美的答案:)
    • 哇!这行得通。我正要扔掉我的笔记本电脑:P 谢谢一束
    【解决方案2】:

    对此有两种可能的常见解释:

    1. 内容长度未知。或者更具体地说,服务器没有在响应消息中设置“Content-Length”标头。

    2. 内容长度大于Integer.MAX_VALUE。如果发生这种情况,getContentLength() 返回-1。 (javadocs 建议使用 getContentLengthLong() 而不是 getContentLength() 以避免该问题。)

    无论哪种方式,最好不要预先分配一个固定大小的字节数组来保存图像。

    • 另一种方法是创建一个本地ByteArrayOutputStream 并将从套接字读取的字节复制到该位置。然后调用toByteArray获取完整的字节数组。

    • 另一种选择是将数据保存在文件系统中的临时文件中。

    显然,造成这种情况的一个常见根本原因是某些实现默认情况下会为响应数据请求“gzip”编码。这会强制服务器将内容长度设置为 -1。你可以这样防止:

    connection.setRequestProperty("Accept-Encoding", "identity");
    

    ... 但这意味着响应不会被压缩。所以就是 (IMO) 不合格的解决方案。


    您现有的客户端代码在另一个方面也存在问题。如果遇到 IOException 或其他异常,代码块将“异常退出”而不关闭 URLConnection。这将导致文件描述符的泄漏。这样做太多次,您的应用程序将由于文件描述符耗尽...或本地端口号而失败。

    最好使用 try / finally 来确保绑定外部资源的 URLConnections、Sockets、Streams 等始终关闭。


    根据(声称的)内容长度预分配缓冲区会使您遭受拒绝服务攻击。想象一下,如果坏人向您发送大量带有危险的“Content-Length”标头的请求,然后缓慢发送数据会怎样。 OOME 或更糟。

    【讨论】:

    • 您在应用程序或服务器端向我推荐的任何更改。我需要在这里添加的任何代码
    • 我确实捕捉到了异常,我还没有把上面的代码贴出来,上面所有的代码都在 try catch 语句中
    • 这不仅仅是捕获异常的问题。您还必须在 finally 块中关闭连接。
    • 您好,我已经添加了我在编辑中使用的方法的完整代码。
    • 是的。我知道了。正如我所料(并且正如我上面解释的),如果在打开连接和关闭 InputStream 之间抛出异常,您的代码很可能会泄漏套接字文件描述符。
    【解决方案3】:

    服务器似乎没有在其响应标头中提供 Content-Length,您是否从响应标头中获得了 Transfer-Encoding=chunked 标头?

    我的情况是:我执行 HttpURLConnection 并认为服务器会以正值向我响应“Content-Length”,但它没有,然后我转向 AndroidHttpClient 哪个android HttpClient 实现,再次执行相同的请求并得到正确的Content-Length。

    我用Wireshark分析了这两个请求,发现请求头有点不同。

    使用 AndroidHttpClient 的头部列表:

    ---------------------------------- request headers
    Range : bytpe=0-
    Host : download.game.yy.com
    Connection : Keep-Alive
    User-Agent : com.duowan.mobile.netroid
    
    ---------------------------------- response headers
    Server : nginx
    Content-Type : text/plain; charset=utf-8
    ETag : "535e2578-84e350"
    Cache-Control : max-age=86400
    Accept-Ranges : bytes
    Content-Range : bytes 0-8708943/8708944
    Content-Length : 8708944
    

    使用 HttpURLConnection 的请求头列表:

    ---------------------------------- request headers
    Range : bytpe=0-
    Host : download.game.yy.com
    Connection : Keep-Alive
    User-Agent : com.duowan.mobile.netroid
    Accept-Encoding : gzip    // difference here
    
    ---------------------------------- response headers
    Server : nginx
    Content-Type : text/plain; charset=utf-8
    Cache-Control : max-age=86400
    Transfer-Encoding : chunked
    X-Android-Received-Millis : 1398861612782
    X-Android-Sent-Millis : 1398861608538
    

    请求头的唯一区别是Accept-Encoding不是我自己添加的,是Android默认设置HttpURLConnection,之后我设置为identity 然后再次执行请求,下面是完整的标头堆栈:

    ---------------------------------- request headers
    Range : bytpe=0-
    Host : download.game.yy.com
    Connection : Keep-Alive
    User-Agent : com.duowan.mobile.netroid
    Accept-Encoding : identity
    
    ---------------------------------- response headers
    Server : nginx
    Content-Type : text/plain; charset=utf-8
    ETag : "535e2578-84e350"
    Cache-Control : max-age=86400
    Accept-Ranges : bytes
    Content-Range : bytes 0-8708943/8708944
    Content-Length : 8708944
    X-Android-Received-Millis : 1398862186902
    X-Android-Sent-Millis : 1398862186619
    

    如您所见,在我将 Accept-Encoding 设置为“identity”替换系统默认值“gzip”后,服务器提供的“Content-Length”为正值,这就是为什么 AndroidHttpClient 可以采用正确的 Content-Length 值和HttpURLConnection 不是。

    gzip压缩编码可能会导致服务器端考虑的分块响应,如果服务器认为可以收到分块编码响应,它可能没有提供Content-Length标头,请尝试禁用gzip可接受的行为然后看看有什么不同。

    【讨论】:

    • 请注意:关闭传输编码可能会导致服务器出现性能问题,因为它很可能无法再“流式传输”您请求的任何内容,并且必须在发送之前“计算”整个响应。最好的计划是不依赖于该标头,而只是流式传输。这与压缩等无关。
    【解决方案4】:

    请看这里:http://download.oracle.com/javase/6/docs/api/java/net/URLConnection.html#getContentLength%28%29

    上面写着,

    返回:

    此连接的 URL 引用的资源的内容长度,如果内容长度未知,则为 -1。

    这只是意味着标题不包含content-length 字段。如果您可以控制服务器代码。您应该以某种方式设置内容长度。类似ServletResponse#setContentLength

    【讨论】:

    • 此连接的 URL 引用的资源的内容长度,如果内容长度未知,则为 -1。
    【解决方案5】:

    我的墙纸应用程序中也遇到了这个问题。问题是因为您的服务器没有在其 http 标头中提供 Content-Length。这是一个关于具有 Content-length 的普通 http 标头的快照。

    我使用的是共享主机,因此无法更改服务器配置。在我的应用程序中,我将进度对话框最大值设置为一个近似值(大于我的实际文件大小),如下所示:

    int filesize = connection.getContentLength();
    if(filesize < 0) {
        progressDialog.setMax(1000000);
    } else {
        progressDialog.setMax(filesize);
    }
    

    你也可以在这里查看我的完整示例源代码:

    Android Progress Dialog Example.

    【讨论】:

      【解决方案6】:

      我在这里迟到了,但这可能会对某人有所帮助。我遇到了同样的问题,当我尝试获取内容长度时,我总是得到 -1 值。

      以前我使用下面的方法来获取内容长度。

      long totalByte=connection.getContentLength();
      

      我用下面的方法解决了我的问题。

      long totalByte=Long.parseLong(connection.getHeaderField("Content-Length"));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-20
        • 1970-01-01
        • 2012-01-01
        • 2014-06-03
        • 2018-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多