Connect getContentLength = -1问题的解决方法

Connector getContentLength = -1问题的解决方法

以下代码是读取通过http读取url内容

           hc = (HttpConnection)Connector.open(url);
            in = hc.openInputStream();
            
            int contentLength = (int)hc.getLength();
            byte[] raw = new byte[contentLength];
            int length = in.read(raw);
            
            in.close();
            hc.close();
  
但当url的内容很少的时候,contentLength 总是返回-1 导致程序出错。

解决的办法是改进读取的方式

            hc = (HttpConnection)Connector.open(url);
            InputStream in = hc.openInputStream();
            System.out.println("hc.getLength()="+hc.getLength()); ;
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[512];
            int rc = 0;
            while ( (rc = in.read(buff, 0, 512)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            byte[] b = swapStream.toByteArray();
            in.close();
            hc.close();

这样就可以正确读出内容了。

http://www.ooohooo.com/viewthread.php?tid=64&extra=page%3D1 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值