入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

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

创建时间:2007-04-06 投稿人: 浏览次数:4889
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 
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
  • 上一篇:没有了
  • 下一篇:没有了
未上传头像