我有下面的方法将一些数据发送到服务器。
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很大,那么它无法POST,我从记录器方法中得到以下错误(Http响应代码:[400])
--xxxx--sendData()----scheduleNetworkRetry()-----networkCode=[400]--START------
--xxxx----scheduleNetworkRetry()---
xxxxx----scheduleNetworkRetry()------ntworkTask = app.utilities.NetworkConnector$NetworkTimeoutTask@efb4d042 Timer = java.util.Timer@1fd138a9
NetworkConnector --- sendData() ------Connection Problem serverResponse Code [400]
--xxx--updateConnectionMessages()---Msg =Server Connection Failed : [Connection Failed..
Http Response Code: [400]]
我将如何解决此错误。注意此错误已在移动设备和模拟器中重新创建
答案 0 :(得分:0)
以下告诉我们,请求已发送到服务器,服务器不喜欢它:
Connection Problem serverResponse Code [400]
(字符串“连接问题”来自您的代码,所以这里有误导性。)
您需要做的下一件事是找出服务器不喜欢的内容。
如果您有权访问服务器,请查找error.log文件。应该提示问题是什么。 某些防火墙也可能阻止了该请求。有时候后变量的最大长度有限制。
如果您无权访问服务器,请尝试使用其他技术发送相同的请求 (html表单,您选择的脚本语言或简单的命令行java app)这样可以更轻松地进行实验以找到问题。