5

我是黑莓新手,我正在尝试将搜索词发布到 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;
}    
4

6 回答 6

4

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");
}
于 2012-06-26T13:15:25.490 回答
2

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

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

这就是 NegativeArraySizeException 的原因。

于 2012-06-26T13:07:12.240 回答
2

我猜你什么时候做

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

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

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

于 2012-06-26T13:08:43.300 回答
1

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

Ref1:Blackberry 发送 HTTPPost 请求

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); 
于 2012-06-26T14:51:38.943 回答
1

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

requestOut = connection.openOutputStream();

我介绍了ByteArrayOutpuStream 它帮助我最终显示输入流。我也改变了发送参数的方式,改用URLEncodedPostDatatype 。由于服务器将我以前的请求解释为 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。我发布了上面的代码来帮助任何有同样问题的人。

聚苯乙烯。我还使用了Kalai 的格式,它非常有用。

于 2012-06-27T11:46:28.247 回答
1

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

唯一初始化的代码是 -

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

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

于 2017-11-21T08:12:17.847 回答