У меня есть метод ниже, который отправляет некоторые данные на сервер.Ошибка сети 400 в J2ME 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;
}
Код работает нормально. Однако я заметил ошибку; если строка dataToSend велика, то он не в состоянии POST, и я получаю следующее сообщение об ошибке (код ответа HTTP: [400]) из моего Logger метода
--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]]
Как будет идти об исправлении этой ошибки. Примечание Этой ошибка была воссоздана в обеих мобильных устройствах и эмуляторе
Я изменил следующий httpConn.setRequestMethod (HttpConnection.POST); к httpConn.setRequestMethod (HttpConnection.GET); и смог исправить проблему на эмуляторе. В настоящее время запросы поступают на сервер, как ожидается от эмулятора, но не на реальном телефоне. На устройстве я все равно получаю ошибку 400. При проверке error_log на сервере ничего не сообщать. Если я использую другой метод, нет ничего плохого и все работает –