在 Android 中使用 httpPost 发送后如何从 servlet 检索 returns 的数据
How to retrieve data which returns from a servlet after I sent it with a httpPost in Android
我使用 HttpPost 将要保存在数据库中的对象发送到 HttpServlet。但是我在Server端保存后,需要取对应的id。那我该怎么做呢?
Gson gson = GsonFactory.getInstance();
String json1;
String url;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
url = this.url + "/saveMyOrder";
nameValuePairs.add(new BasicNameValuePair("process", "save"));
Order object = new Order();
object.setName("Order");
object.setTime(new Date());
json1 = gson.toJson(object);
nameValuePairs.add(new BasicNameValuePair("json", json1));
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = HttpOperations.httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
Toast.makeText(getApplicationContext(), "Success ... ",
Toast.LENGTH_LONG).show();
finish();
} else {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this)
.setMessage("ERROR!").setCancelable(true);
dlgAlert.show();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
我试着把我的代码转换成英文,所以如果你有什么不明白的地方,尽管问。
我在 my research 后解决了我的问题。答案是:
字符串数据=EntityUtils.toString(response.getEntity());
它returns你的数据作为字符串在你post它之后。
我使用 HttpPost 将要保存在数据库中的对象发送到 HttpServlet。但是我在Server端保存后,需要取对应的id。那我该怎么做呢?
Gson gson = GsonFactory.getInstance();
String json1;
String url;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
url = this.url + "/saveMyOrder";
nameValuePairs.add(new BasicNameValuePair("process", "save"));
Order object = new Order();
object.setName("Order");
object.setTime(new Date());
json1 = gson.toJson(object);
nameValuePairs.add(new BasicNameValuePair("json", json1));
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = HttpOperations.httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
Toast.makeText(getApplicationContext(), "Success ... ",
Toast.LENGTH_LONG).show();
finish();
} else {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this)
.setMessage("ERROR!").setCancelable(true);
dlgAlert.show();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
我试着把我的代码转换成英文,所以如果你有什么不明白的地方,尽管问。
我在 my research 后解决了我的问题。答案是:
字符串数据=EntityUtils.toString(response.getEntity());
它returns你的数据作为字符串在你post它之后。