负数组大小异常

时间:2012-06-26 13:02:39

标签: http post blackberry java-me

我是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;
}    

6 个答案:

答案 0 :(得分:3)

connection.getLength()正在返回 -1

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

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

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

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

答案 1 :(得分:2)

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

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

这就是NegativeArraySizeException的原因。

答案 2 :(得分:1)

我猜你什么时候

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

InputStream不知道它的长度,因此返回-1。

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

答案 3 :(得分:1)

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

参考1:Blackberry send a HTTPPost request

参考2: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); 

答案 4 :(得分:1)

发现它!我忘了打开输出流连接

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,这非常有用。

答案 5 :(得分:0)

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

初始化的唯一代码是 -

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

在初始化数组

之前,您可能需要添加长度检查