0

I am trying to download images into byte array but it gives me an error message,

What should i do?? please help me guys

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

1 回答 1

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

看看这个答案来解决这个问题。

于 2013-05-29T07:56:25.737 回答