Android传数据到服务器端
在之前的博客中提到主线程中不能操作耗时的操作,例如网络操作。
今天使用实例来使用AsnycTask。
public Robot query(Robot rqRobot) {
Gson gson=new Gson();
String url= MyData.URL+"RobotServlet";
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost(url);
List<NameValuePair> rqParmeter=new ArrayList<>();
rqParmeter.add(new BasicNameValuePair("input",gson.toJson(rqRobot)));
try {
post.setEntity(new UrlEncodedFormEntity(rqParmeter, HTTP.UTF_8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Robot rpRobot=null;
Log.e("niinin","----------------------------");
try {
HttpResponse httpResponse=client.execute(post);
int statusCode= httpResponse.getStatusLine().getStatusCode();
Log.e("dsdsd",statusCode+"");
if (statusCode==200){
HttpEntity httpEntity= httpResponse.getEntity();
Log.e("niinin",httpResponse.getEntity().toString());
rpRobot=gson.fromJson(EntityUtils.toString(httpEntity),Robot.class);
}
} catch (IOException e) {
e.printStackTrace();
}
return rpRobot;
}
执行client上传数据,接收到的就是返回值:
HttpResponse response = client.execute(post);
得到返回值:response.getEntity()
但是得到的返回值不是字符串,要先把他转为字符串:
使用EntityUtils的方法来转化为字符串
EntityUtils.toString(response.getEntity());
// setting request parameters
List<NameValuePair> requestParameters = new ArrayList<>();
// send imageSize parameter to server for recognition
requestParameters.add(new BasicNameValuePair("action", "findById"));
requestParameters.add(new BasicNameValuePair("imageSize", "400"));
requestParameters.add(new BasicNameValuePair("id", Integer
.toString(spotId)));
try {
//要将list转化为转化为Entity,可以调用UrlEncodedFormEntity方法转化
post.setEntity(new UrlEncodedFormEntity(requestParameters,
HTTP.UTF_8));