欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Java NegativeArraySizeException异常解决方案

时间:2022-06-09 09:20:42|栏目:JAVA代码|点击:

问题描述:服务器接收后台返回的报文时,提示java.lang.NegativeArraySizeException

分析:这种异常返回的原因,一般情况下没有报文提示为返回空报文,初步分析是响应报文流长度出了问题

百度一下类似的情况:https://stackoverflow.com/questions/11207897/negative-array-size-exception

节选部分内容:

try{
     connection = (HttpConnection)Connector.open("http://someurl.xml",Connector.READ_WRITE);
     URLEncodedPostData postData = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, false);
     postData.append("username", "loginapi");
     postData.append("password", "myapilogin");
     postData.append("term", word);
 
     connection.setRequestMethod(HttpConnection.POST);
     connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
     connection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.0");
     requestOut = connection.openOutputStream();
     requestOut.write(postData.getBytes());
     String contentType = connection.getHeaderField("Content-type");
     detailIn = connection.openInputStream();        
     int length = (int) connection.getLength();
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     if(length > 0){//这里长度没有判定的情况下,byte array长度若为-1会产生错误
         byte info[] = new byte[length];
         int bytesRead = detailIn.read(info);
         while(bytesRead > 0) {
             baos.write(info, 0, bytesRead);
             bytesRead = detailIn.read(info);
             }
         baos.close();
         connection.close();
         requestSuceeded(baos.toByteArray(), contentType);
 
         detailIn.read(info);
     }
     else
     {
          System.out.println("Negative array size");
     }
           requestOut.close();
           detailIn.close();
           connection.close();
    }

  结论:HTTP服务器在返回响应报文的时候,没有进行content.length长度判断,按照常规流程响应了错误长度的报文,导致了接收方报文长度异常

上一篇:Java实现的权重算法(按权重展现广告)

栏    目:JAVA代码

下一篇:如何使用try-with-resource机制关闭连接

本文标题:Java NegativeArraySizeException异常解决方案

本文地址:http://www.codeinn.net/misctech/204247.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有