我正在尝试使用 JSON 在 android 应用和服务器之间发送和接收数据,但遗憾的是我无法执行此操作很多,但没有帮助。我的代码如下:
在android中
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("fromDate", from);
jsonObject.put("toDate", to);
jsonObject.put("reason", reas);
new SendData().execute(jsonObject);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
然后我的 asynctask 的doInBackground方法
try {
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
CmsInter.TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, CmsInter.TIMEOUT);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost httpPost = new HttpPost(getResources().getString(
R.string.URL));
StringEntity se = new StringEntity(object.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
httpPost.setEntity(se);
HttpResponse response = client.execute(httpPost);
message = Sync.convertResponseToString(response);
} catch (Exception e) {
e.printStackTrace();
message = e.toString();
}
然后在servlet代码的doPost()
方法中的服务器端如下:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
StringBuffer sb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
sb.append(line);
} catch (Exception e) { /* report an error */
e.printStackTrace();
}
String str = sb.toString();
try {
org.json.JSONObject json = new org.json.JSONObject(str);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我认为这不是在服务器端阅读JSONObject
的正确方法,因为当我运行此操作时,我会遇到org.json.JSONException: A JSONObject text must begin with '{' at character 1
异常,任何人都可以帮助我解决这个问题。任何帮助将不胜感激。谢谢。
答案 0 :(得分:0)
最后得到它这行错误object.toString()
发送它时应该是object[0].toString()
,因为asynctask的doInBackground方法参数是一个数组,即protected String doInBackground(JSONObject... object)
。