Http 负数组大小异常

Http 负数组大小异常,http,post,blackberry,java-me,Http,Post,Blackberry,Java Me,我是黑莓的新手,我正在尝试用xml将搜索词发布到服务器上。但是我一直收到这个错误请求失败。原因Java.lang.NegativeArraySizeException 在解析数据之前,我想检查连接是否工作,因此我希望从这个连接接收xml格式的响应文本。代码如下: public void webPost(String word) { word = encode (word); String responseText; try{ HttpConnection

我是黑莓的新手,我正在尝试用xml将搜索词发布到服务器上。但是我一直收到这个错误
请求失败。原因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;
}    
publicsvoidwebpost(字符串字){
word=编码(word);
字符串响应文本;
试一试{
HttpConnection=(HttpConnection)连接器。打开(“http://some xml“;
setRequestMethod(HttpConnection.POST);
connection.setRequestProperty(“内容类型”、“应用程序/x-www-form-urlencoded”);
String postData=“username=loginapi&password=myapilogin&term=“+word;
connection.setRequestProperty(“Content-Length”,Integer.toString(postData.Length());
connection.setRequestProperty(“用户代理”、“配置文件/MIDP-2.0配置/CLDC-1.0”);
OutputStream requestOut=连接。openOutputStream();
write(postData.getBytes());
InputStream detailIn=connection.openInputStream();
字节信息[]=新字节[(int)connection.getLength()];
详细阅读(信息);
detailIn.close();
requestOut.close();
connection.close();
responseText=新字符串(信息);
requestSuceeded(requestOut.toString(),responseText);
}
捕获(例外情况除外){
requestFailed(例如toString());
}
}
私有void请求成功(字符串结果、字符串响应文本){
if(responseText.startsWith(“text/xml”){
字符串strResult=新字符串(结果);
已同步(UiApplication.getEventLock()){
textOutputField.setText(strResult);
} 
}否则{
已同步(UiApplication.getEventLock()){
警报(“未知内容类型:+responseText”);
} 
} 
} 
公共无效请求失败(最终字符串消息){
UiApplication.getUiApplication().invokeLater(新的Runnable(){
public void run(){
对话框。警报(“请求失败。原因:+消息”);
} 
}); 
} 
专用字符串编码(字符串文本输入){
//为http post编码文本
textIn=textIn.replace(“+”);
字符串textout=“”;
对于(int i=0;i
我假设
connection.getLength()
在这里尝试初始化数组时返回-1:

byte info[]=new byte[(int)connection.getLength()];
这就是NegativeArraySizeException的原因。

我想当你这么做的时候

byte info[]=new byte[(int)connection.getLength()];
InputStream不知道其长度,因此返回-1


请参阅连接。getLength()正在返回-1

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

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

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

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

参考文献1:

参考文献2:

大概是这样的:

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

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

requestOut=connection.openOutputStream()

我引入了
ByteArrayOutpuStream
,它帮助我最终显示了输入流。我还改变了发送参数的方式,改为使用
URLEncodedPostData
type。因为服务器将我以前的请求解释为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();
    }
另外,我发布上述代码是为了帮助任何有同样问题的人


PPS。我还使用了它,它的作用非常好。

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

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

在初始化数组之前,您可能需要添加一个长度检查

当您说//performance operations时的可能重复项,您的意思如下:
int length=(int)connection.getLength();如果(长度>0){byte info[]=新字节[length];detailIn.read(信息);detailIn.close();requestOut.close();connection.close();responseText=新字符串(信息);requestSuceeded(requestOut.toString(),responseText)因为我做了,但是现在我没有得到任何回应@kalai@michael92是的。您是否收到任何错误?检查是否为“负数组大小”字符串是否已打印。明白了!我将OutputStream更改为ByteArrayOutputStream,并引入
string contentType=connection.getHeaderField(“内容类型”);
但现在它给了我字符串post数据中的术语,我指的是我发布的数据,而不是搜索结果:(any help@Kalai@Jite@aureliani现在修改了它,它似乎在生成一个“get”而不是“post”