Java me J2ME http Post中的网络错误400

Java me J2ME http Post中的网络错误400,java-me,http-post,Java Me,Http Post,我使用下面的方法将一些数据发送到服务器 public String postData(String serverUrl, String dataToSend) { MessageLogger.logMsg("\n--xxxx--postData()------START-----url : [" + serverUrl + "]\n-----xxxx--dataToSend :[" + dataToSend + "]"); String strResponse = ""; //w

我使用下面的方法将一些数据发送到服务器

public String postData(String serverUrl, String dataToSend) {
    MessageLogger.logMsg("\n--xxxx--postData()------START-----url : [" + serverUrl + "]\n-----xxxx--dataToSend :[" + dataToSend + "]");
    String strResponse = ""; //we have not received any response from the Server at this point.
    StringBuffer sb = new StringBuffer("");
    HttpConnection httpConn = null;
    DataInputStream inputStream = null;
    DataOutputStream outStream = null;

    try {
        //convert the dataToSend to byte array.
        byte[] dataToSendBytes = dataToSend.getBytes();

        //open the Connection to the server.
        httpConn = (HttpConnection) Connector.open(serverUrl, Connector.READ_WRITE, true);
        if (httpConn != null) {
            httpConn.setRequestMethod(HttpConnection.POST); // method used to send the data.
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConn.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
            //httpConn.setRequestProperty("Content-Language", "en-US"); //language to use.
            httpConn.setRequestProperty("Connection", "Close"); //connection should be closed after request is finished==>solves persistentConnection Error.
            //setting the Content-length could have issues with some Servers===>
            //if the dataToSend is Empty String => contentLen = 0 , else get length of the dataBytes.
            String contentLen = ((dataToSend.length() > 0) ? Integer.toString(dataToSend.getBytes().length) : Integer.toString(0));
            httpConn.setRequestProperty("Content-length", contentLen); //not working on Emulator ....enable on shipping application.

            if (!dataToSend.equals("null") || dataToSend.length() > 0) {
                //At times we dont have any data to send to the Server so check the Length of the datatosend before opening the outStream.
                //open the output Stream to send data to the Server.
                outStream = httpConn.openDataOutputStream();
                int len = dataToSendBytes.length;
                for (int i = 0; i < len; i++) {
                    outStream.writeByte(dataToSendBytes[i]); //send the data to the Server
                }

                //closeOutStream(outStream);//close outputStream after sending the Data.
            }

            //get response code on Sending Data===> getting response code automatically flushes the output data.
            ntworkResponseCode = httpConn.getResponseCode();

            //create a network Timeout Task that checks the connection after 10seconds.
            scheduleNetworkRetry(); ///===>invoke this when catching Errors ===>response ="" throws IOexception.

            if (ntworkResponseCode == HttpConnection.HTTP_OK) {
                //connection to server was ok -----read response from server
                stopNetworkTimer(); //Server Connection Ok stop timer to avoid interuption during Reading==>Timer will be started by ReadTimer if Required.
                //show that the connection was successful.
                cmdHandler.updateConnectionMessages(" Server Connection Successful.....\n Fetching Data.....\n");
                MessageLogger.logMsg("NetworkConnector---sendData()---Connection Successful.---response Code [" + ntworkResponseCode + "]");
                if (httpConn != null) {
                    //read the Response From the Server-----------
                    inputStream = new DataInputStream(httpConn.openInputStream()); // open the inputStream.

                    //start the ReadTimer before we start Reading Response From Server
                    readTimer.startReadTimer();

                    int read;
                    while ((read = inputStream.read()) != -1) {
                        sb.append((char) read);

                        readTimer.resetCounter(); //reset the timer on every read of a character==>to be fair to waitTime.
                    }

                    //stop the readTimerThread we have finished...reading
                    readTimer.stopReadTimer();
                    stopNetworkTimer();//stop timer here we are done reading response

                    //store the server response in a String.
                    strResponse = sb.toString();

                    if (strResponse.equals("")) {
                        //failed to Get Response From Server throw an IOException
                        cmdHandler.updateConnectionMessages(" Failed to Get Server Response :[" + strResponse + "] \n");
                        throw new IOException(" Failed to Get Server Response: [" + strResponse + "]");
                    }

                    MessageLogger.logMsg("------sendData()---serverResponse =[" + strResponse + "]");
                }
            } else {
                //connection problem occured.
                MessageLogger.logMsg("NetworkConnector --- sendData() ------Connection Problem  serverResponse Code [" + ntworkResponseCode + "]");
                //connection failed throw connectionException
                throw new IOException("Connection Failed..\n Http Response Code: [" + ntworkResponseCode + "]");
            }

        }// the httpConnection Not null.--end.

    } catch (IllegalArgumentException arge) {
        MessageLogger.logErrorMsg("--------------sendData() --IllegalArgumentException:[" + arge.getMessage() + "]");
        strResponse = CONNECTION_EXCEPTION;
    } catch (ConnectionNotFoundException cone) {
        MessageLogger.logErrorMsg("--------------sendData() ---ConnNotFoundException: [" + cone.getMessage() + "]");
        strResponse = CONNECTION_EXCEPTION;
        retryConnection = true;
        //show the exception generated by the Server.
        cmdHandler.updateConnectionMessages("Connection Not Found :[" + cone.getMessage() + "]\n");
        // retry the connection to the server.
        scheduleNetworkRetry();
    } catch (IOException ioe) {
        MessageLogger.logErrorMsg("--------------sendData() ----IOException :[ " + ioe.getMessage() + "]");
        strResponse = CONNECTION_EXCEPTION;
        retryConnection = true;
        //show the exception genereated by the server.
        cmdHandler.updateConnectionMessages("Connection Problem\n : [" + ioe.getMessage() + "]\n");
        // retry the connection to the server.
        scheduleNetworkRetry();
    } catch (SecurityException se) {
        //user cancelled the Connection Request.
        MessageLogger.logErrorMsg("--------------sendData() -----SecurityException :[" + se.getMessage() + "]");
        strResponse = CONNECTION_EXCEPTION;
    } finally {
        //close all the connection streams
        try {
            if (inputStream != null) {
                //close the inputStream
                inputStream.close();
                inputStream = null;
            }

            if (outStream != null) {
                //close the outStream.
                outStream.close();
                outStream = null;
            }

            if (httpConn != null) {
                //close  the connection object.
                httpConn.close();
                httpConn = null;
            }

        } catch (IOException ie) {
            MessageLogger.logErrorMsg("Finally----Exception : [" + ie.getMessage() + "]");
        }
        MessageLogger.logMsg("--finally----END--------inside Finally-----httpCon=" + httpConn + "instream = " + inputStream);

    }
    MessageLogger.logMsg("---xxxx---postData()------------END--------responseGot =[ " + strResponse + " ]\n ----maxConnReached=[" + connectionMaxReached + "]-----");
    return strResponse;
}

我该如何着手纠正这个错误呢。注意:此错误已在移动设备和Emulator中重新创建。下面告诉我们,请求已发送到服务器,服务器不喜欢它:

Connection Problem  serverResponse Code [400]
(字符串“Connection Problem”来自您的代码,因此在这里有误导性)

接下来需要做的事情是找出服务器不喜欢什么

如果您有权访问服务器,请查找error.log文件。应该有一个提示是什么问题。 也可能是某种防火墙阻止了请求。有时,后置变量的最大长度是有限制的

如果您无法访问服务器,请尝试使用不同的技术发送相同的请求
(html表单、您选择的脚本语言或简单的命令行java应用程序)这使实验更容易找到问题。

我更改了以下httpConn.setRequestMethod(HttpConnection.POST);到httpConn.setRequestMethod(HttpConnection.GET);并且能够在模拟器上解决这个问题。现在的情况是,请求按预期从emulator到达服务器,但不是在真实的电话上。在设备上,我仍然得到错误400。检查服务器上的错误日志时,没有任何可报告的内容。如果使用其他方法,则没有任何错误,并且一切正常
Connection Problem  serverResponse Code [400]