在尝试从url下载图像时,它会给出缓冲区容量错误

时间:2013-05-29 07:04:28

标签: 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;
}

1 个答案:

答案 0 :(得分:3)

查看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”标头。

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