2014-02-17 49 views
0

我有下面的方法发送一些数据到服务器。J2ME中的网络错误400 http后

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

该代码工作正常。但是我注意到一个Bug;如果String dataToSend较大,则它没有张贴和我得到以下错误(HTTP响应代码:[400])从我的记录器方法

--xxxx--sendData()----scheduleNetworkRetry()-----networkCode=[400]--START------ 
--xxxx----scheduleNetworkRetry()--- 
xxxxx----scheduleNetworkRetry()------ntworkTask =  [email protected] Timer = [email protected] 
NetworkConnector --- sendData() ------Connection Problem serverResponse Code [400] 
--xxx--updateConnectionMessages()---Msg =Server Connection Failed : [Connection Failed.. 
Http Response Code: [400]] 

我怎么会去纠正这个错误。注意此错误已重新在这两个移动设备和仿真器

回答

0

下面告诉我们,请求sended到服务器,服务器不喜欢它:

Connection Problem serverResponse Code [400] 

(字符串“连接问题”来自你的代码,所以这里有误导)。

接下来你需要做的是找出服务器不喜欢的东西。

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

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

+0

我改变了以下httpConn.setRequestMethod(HttpConnection.POST);到httpConn.setRequestMethod(HttpConnection.GET);并能够解决模拟器上的问题。现在看来,这些请求按照预期从仿真器到达服务器,但不是真正的手机。在设备上,我仍然得到了错误400.在检查服务器上的error_log时,没有什么可报告的。如果我使用其他方法,那么没有任何问题,并且一切正常 –