問題描述:服務器接收后台返回的報文時,提示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長度判斷,按照常規流程響應了錯誤長度的報文,導致了接收方報文長度異常