negativearraysizeexception(如何解决Java中NegativeArraySizeException异常的问题)

发布时间:2025-12-11 00:45:55 浏览次数:1

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

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

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

节选部分内容:

try{connection=(HttpConnection)Connector.open("http://someurl.xml",Connector.READ_WRITE);URLEncodedPostDatapostData=newURLEncodedPostData(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.0Configuration/CLDC-1.0");requestOut=connection.openOutputStream();requestOut.write(postData.getBytes());StringcontentType=connection.getHeaderField("Content-type");detailIn=connection.openInputStream();intlength=(int)connection.getLength();ByteArrayOutputStreambaos=newByteArrayOutputStream();if(length>0){//这里长度没有判定的情况下,bytearray长度若为-1会产生错误byteinfo[]=newbyte[length];intbytesRead=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("Negativearraysize");}requestOut.close();detailIn.close();connection.close();}

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

negativearraysizeexception
需要做网站?需要网络推广?欢迎咨询客户经理 13272073477