[英]Passing data between android and server using JSON parsing
I'm trying to send and receive data between android app and server using JSON but unfortunately i am unable to do it i searched a lot but it didn't help. 我正在尝试使用JSON在android应用程序和服务器之间发送和接收数据,但不幸的是我无法做到这一点,但是我搜索了很多,但没有帮助。 My code is as follows:
我的代码如下:
In 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();
}
and then my asynctask 's doInBackground method 然后我的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();
}
and then on server side within the doPost()
method of servlet code is as follows : 然后在服务器端,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();
}
}
and I think this is not the right way to read JSONObject
on the server side because when I run this I get org.json.JSONException: A JSONObject text must begin with '{' at character 1
exception , Can anyone please help me out in this. 而且我认为这不是在服务器端读取
JSONObject
的正确方法,因为在运行此命令时,我会收到org.json.JSONException: A JSONObject text must begin with '{' at character 1
异常org.json.JSONException: A JSONObject text must begin with '{' at character 1
,有人可以帮我吗这个。 Any help will be appreciated. 任何帮助将不胜感激。 Thanks.
谢谢。
终于明白了这一行是错误的object.toString()
发送时应该是object[0].toString()
因为asynctask的doInBackground方法参数是一个数组,即protected String doInBackground(JSONObject... object)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.