【问题标题】:Negative Array Size Exception负数组大小异常
【发布时间】:2012-06-26 13:02:39
【问题描述】:

我是 Blackberry 的新手,我正在尝试在 xml 中将搜索词发布到服务器。但我不断收到此错误Request Failed. Reason Java.lang.NegativeArraySizeException

我想在解析数据之前检查连接是否有效,所以从这个连接中,我希望收到 xml 中的响应文本。下面是代码:

public void webPost(String word) {
    word = encode (word);
    String responseText;
    try{
        HttpConnection connection = (HttpConnection)Connector.open("http://some url.xml");
        connection.setRequestMethod(HttpConnection.POST);
        connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        String postData = "username=loginapi&password=myapilogin&term="+ word;
        connection.setRequestProperty("Content-Length",Integer.toString(postData.length()));
        connection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.0");
        OutputStream requestOut = connection.openOutputStream();
        requestOut.write(postData.getBytes());

        InputStream detailIn = connection.openInputStream();
        byte info[]=new byte[(int)connection.getLength()];
        detailIn.read(info);
        detailIn.close();
        requestOut.close();
        connection.close();
        responseText=new String(info);
        requestSuceeded(requestOut.toString(), responseText);
    }
    catch(Exception ex){
        requestFailed(ex.toString());
    }
}

private void requestSuceeded(String result, String responseText) {
    if(responseText.startsWith("text/xml")) { 
        String strResult = new String(result); 
        synchronized(UiApplication.getEventLock()) { 
            textOutputField.setText(strResult); 
        } 
    } else{ 
        synchronized(UiApplication.getEventLock()) { 
            Dialog.alert("Unknown content type: " + responseText); 
        } 
    } 
} 

public void requestFailed(final String message) { 
    UiApplication.getUiApplication().invokeLater(new Runnable() { 
        public void run() { 
            Dialog.alert("Request failed. Reason: " + message); 
        } 
    }); 
} 

private String encode(String textIn) {
     //encode text for http post
    textIn = textIn.replace(' ','+');
    String textout = "";
    for(int i=0;i< textIn.length();i++){
        char wcai = textIn.charAt(i);
        if(!Character.isDigit(wcai) && !Character.isLowerCase(wcai) && !Character.isUpperCase(wcai) && wcai!='+'){
            switch(wcai){
                case '.':
                case '-':
                case '*':
                case '_':
                    textout = textout+wcai;
                    break;
                default:
                    textout = textout+"%"+Integer.toHexString(wcai).toUpperCase();//=textout.concat("%").concat(Integer.toHexString(wcai));
            }
        }else{
            textout = textout+wcai;//=textout.concat(wcai+"");
        }
    }
    return textout;
}    

【问题讨论】:

标签: http post blackberry java-me


【解决方案1】:

connection.getLength() 正在返回 -1

在创建信息数组之前,检查连接的长度。

int length = (int) connection.getLength();

if(length > 0){
     byte info[]=new byte[length];
     // perform operations

}else{
     System.out.println("Negative array size");
}

【讨论】:

  • 当您说//执行操作时,您的意思是这样的:int length = (int) connection.getLength(); if(length &gt; 0){ byte info[] = new byte[length]; detailIn.read(info); detailIn.close(); requestOut.close(); connection.close(); responseText=new String(info); requestSuceeded(requestOut.toString(),responseText);,因为我这样做了,但现在我没有得到任何回应。 @kalai
  • @michael92 是的。你有什么错误吗?检查是否打印了“Negative array size”字符串。
  • 知道了!我将 OutputStream 更改为 ByteArrayOutputStream 并引入 String contentType = connection.getHeaderField("Content-type"); 但现在它为我提供了字符串发布数据中的术语,我的意思是我发布的数据而不是搜索结果:(任何帮助 @Kalai @Jite @Aurelien
  • 我现在修改了它,它似乎是在做一个“get”而不是“post”
【解决方案2】:

我假设connection.getLength() 在您尝试在此处初始化数组时返回 -1:

byte info[]=new byte[(int)connection.getLength()];

这就是 NegativeArraySizeException 的原因。

【讨论】:

    【解决方案3】:

    我猜你什么时候做

    byte info[]=new byte[(int)connection.getLength()];
    

    InputStream 不知道它的长度,所以它返回 -1。

    http://www.velocityreviews.com/forums/t143704-inputstream-length.html

    【讨论】:

      【解决方案4】:

      参考:http://supportforums.blackberry.com/t5/Java-Development/HttpConnection-set-to-POST-does-not-work/m-p/344946

      参考1:Blackberry send a HTTPPost request

      Ref2:http://www.blackberryforums.com/developer-forum/181071-http-post-passing-parameters-urls.html

      类似这样的:

      URLEncodedPostData postData = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, true); 
      postData.append("name",name); 
      

      【讨论】:

        【解决方案5】:

        找到了!我忘了打开输出流连接

        requestOut = connection.openOutputStream();

        我介绍了ByteArrayOutpuStream,它帮助我最终显示了输入流。我也改变了发送参数的方式,改用URLEncodedPostData 类型。由于服务器将我以前的请求解释为 GET 而不是 POST。而我现在要做的就是解析进来的信息。

        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 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();
            }
        

        PS。我发布了上面的代码来帮助任何有同样问题的人。

        PPS。我还使用了Kalai's format,它非常有用。

        【讨论】:

          【解决方案6】:

          java.lang.NegativeArraySizeException 表示您正在尝试初始化一个负长度的数组。

          唯一正在初始化的代码是 -

          byte info[]=new byte[(int)connection.getLength()];
          

          您可能希望在初始化数组之前添加长度检查

          【讨论】:

            猜你喜欢
            • 2019-01-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-07-16
            • 2016-09-14
            • 1970-01-01
            • 2012-07-05
            相关资源
            最近更新 更多