java - 尝试从 url 下载图像时,出现缓冲区容量错误

标签 java android

我正在尝试将图像下载到字节数组中,但它给了我一条错误消息,

我该怎么办?请大家帮帮我

05-29 12:28:13.324: D/ImageManager(6527): Error: java.lang.IllegalArgumentException: Buffer capacity may not be negative

byte []bg1=getLogoImage("http://onlinemarketingdubai.com/hotelmenu/images/874049310_gm.png");


private byte[] getLogoImage(String url){
    try {
        Log.d("Url",url);
        URL imageUrl = new URL(url);
        URLConnection ucon = imageUrl.openConnection();
        HttpURLConnection conn= (HttpURLConnection)imageUrl.openConnection();
        conn.setDoInput(true);
        conn.connect();
        int length = conn.getContentLength();
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        ByteArrayBuffer baf = new ByteArrayBuffer(length);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        return baf.toByteArray();
    } catch (Exception e) {
        Log.d("ImageManager", "Error: " + e.toString());
    }
return null;
}

最佳答案

看一下 ByteArrayBuffer 类:

public final class ByteArrayBuffer  {

  private byte[] buffer;
  private int len;

  public ByteArrayBuffer(int capacity) {
      super();
      if (capacity < 0) {
       throw new IllegalArgumentException("Buffer capacity may not be negative");
      }

您正在初始化它,并将 length 值传递给它,作为您从中获取的缓冲区的capacity:

int length = conn.getContentLength();

所以问题来自于连接长度,我认为它是-1,因为内容长度未知。服务器可能没有在响应消息中设置“Content-Length” header 。

看看这个 answer来解决这个问题。

关于java - 尝试从 url 下载图像时,出现缓冲区容量错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16807520/

相关文章:

java - 包 org.springframework.cloud.netflix.zuul 不存在

java - 无法从 Spring Boot Controller 获取 web.xml 中的上下文参数

java - Android向圆弧边缘添加线标记

android - 有没有办法专门为Android指定CSS

java - AndroidLocationPlayServiceManager 上的构建错误

java - 在 Android 本地存储来自 JSON Feed 的数据

java - Bazel 和系统环境变量

java - 如何获取ArrayList <String>中所有字符串的总长度?

android - 为什么即使被要求不绑定(bind),Android 也会绑定(bind)?

AndroidManifest.xml 不存在或具有不正确的 React Native 根标记