Android 服务端将位置信息发送给客户端的实现
一、问题
Android服务端将位置信息发送给客户端
二、环境
AndroidStudioEclipse
三、代码实现
服务端Servlet调用Dao层在数据库中查找数据,在servlet中将查找到的数据汇集成json字符串(json数组形式)。
服务端:
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
//response.setContentType("text/plain;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
ServerToParentDaostpDao=newServerToParentDao();
//Stringnum=mtpDao.query();
//System.out.println(num);
PrintWriterout=response.getWriter();
StringBuffersb=newStringBuffer();
sb.append('[');
ListaddrList=stpDao.queryOne();
for(Addressaddress:addrList){
sb.append('{').append("\"id\":").append(""+address.getId()+"").append(",");
sb.append("\"latitude\":").append("\""+address.getLatitude()+"\"").append(",");
sb.append("\"longitude\":").append("\""+address.getLongitude()+"\"").append(",");
sb.append("\"time\":\"").append(address.getTime());
sb.append("\"}").append(",");
}
sb.deleteCharAt(sb.length()-1);
sb.append(']');
out.write(sb.toString());
System.out.println(sb.toString());
//request.setAttribute("json",sb.toString());
//request.getRequestDispatcher("watch.jsp").forward(request,response);
//out.write(num);
//response.getOutputStream().write(mtpDao.query().getBytes("UTF-8"));
out.flush();
out.close();
//System.err.println(request.getParameter(""));
//System.out.println(code);
System.out.println("连接成功");
//PrintWriterprintWriter=response.getWriter();
//printWriter.print("客户端你好,数据连接成功!");
//printWriter.flush();
//printWriter.close();
}
客户端:
sendButton.setOnClickListener(newView.OnClickListener(){
@Override
publicvoidonClick(Viewv){
HttpPosthttpRequest=newHttpPost("http://192.168.159.1:8080/MyAndroidServer/ServerToParentServlet");
Listparams=newArrayList();
//Stringstr="1";
//params.add(newBasicNameValuePair("Code",str));
Log.i("MY3","HasDone");
try{
//httpRequest.setEntity(newUrlEncodedFormEntity(params,HTTP.UTF_8));//设置请求参数项
HttpClienthttpClient=newDefaultHttpClient();
HttpResponsehttpResponse=httpClient.execute(httpRequest);//执行请求返回响应
if(httpResponse.getStatusLine().getStatusCode()==200){//判断是否请求成功
HttpEntityentity=httpResponse.getEntity();
if(entity!=null){
System.out.println("---------");
//System.out.println("Responecontent"+EntityUtils.toString(entity,"UTF-8"));
Intentintent=newIntent(ParentRequest.this,MainActivity.class);
intent.putExtra("jsonString",EntityUtils.toString(entity,"UTF-8"));
startActivity(intent);
}
Log.i("MY2","HasDone");
}else{
Toast.makeText(ParentRequest.this,"没有获取到Android服务器端的响应!",Toast.LENGTH_LONG).show();
}
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(UnsupportedEncodingExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
});
请求地址书写形式:http://主机IP地址:端口号/项目名/action名
HttpPost方式建立连接,HttpResponse.getEntity()获取响应信息,EntityUtils.toString(entity,“UTF-8”)将entity转为String字符串,Intent将JSON字符串传递到其他activity页面中去。
JSON字符串解析类:
publicstaticListgetAddress(StringjsonStr)
throwsJSONException{
/*******************解析***********************/
//初始化list数组对象
ListmList=newArrayList();
Addressaddress=newAddress();
JSONArrayarray=newJSONArray(jsonStr);
for(inti=0;i
我这个是当时在做一个儿童定位写的,数据库设计没思考全面,思维比较狭隘。
应该思考到的是儿童信息表中儿童信息要跟父母表中父母信息对应起来,即这APP是给多对父母和孩子使用的,而不是一对父母与孩子。
服务端也不应该是使用本地的,应该使用云服务器,这样就不会被同一局域网所限制。
Android客户端将位置信息发送给服务端
代码实现
客户端:
HttpPosthttpRequest=newHttpPost("http://192.168.159.1:8080/MyAndroidServer/ChildrenToServerServlet");
Listparams=newArrayList();
SimpleDateFormatsimpleDateFormat=newSimpleDateFormat("yyyy-MM-dd-HH:mm");
Datedate=newDate(System.currentTimeMillis());
Stringstr=simpleDateFormat.format(date);
System.out.println(str);
params.add(newBasicNameValuePair("Time",str));
params.add(newBasicNameValuePair("Latitude",latitude));
params.add(newBasicNameValuePair("Longitude",longitude));
try{
httpRequest.setEntity(newUrlEncodedFormEntity(params,HTTP.UTF_8));//设置请求参数项
HttpClienthttpClient=newDefaultHttpClient();
HttpResponsehttpResponse=httpClient.execute(httpRequest);//执行请求返回响应
if(httpResponse.getStatusLine().getStatusCode()==200){//判断是否请求成功
//Toast.makeText(ChildrenToServerActivity.this,EntityUtils.toString(httpResponse.getEntity()),Toast.LENGTH_LONG).show();
Intentintent=newIntent();
intent.setAction("cn.abel.action.broadcast");
intent.putExtra("Response",EntityUtils.toString(httpResponse.getEntity()));
context.sendBroadcast(intent);
}else{
//Toast.makeText(MainActivity.this,"没有获取到Android服务器端的响应!",Toast.LENGTH_LONG).show();
Intentintent=newIntent();
intent.setAction("cn.abel.action.broadcast");
intent.putExtra("Response","没有获取到Android服务器端的响应!");
context.sendBroadcast(intent);
}
}catch(UnsupportedEncodingExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
params.add(newBasicNameValuePair(“Time”,str));
Time是str的变量名,用于服务端接收数据用的。
这是用来添加要传递给服务端的数据,为String字符串形式。
服务端:
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
response.setContentType("text/plain;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
Stringtime=request.getParameter("Time");
Stringlatitude=request.getParameter("Latitude");
Stringlongitude=request.getParameter("Longitude");
ChildrenToAddressDaoaddressDao=newChildrenToAddressDao();
addressDao.insert(latitude,longitude,time);
System.err.println(request.getParameter("Time"));
System.err.println(request.getParameter("Latitude"));
System.err.println(request.getParameter("Longitude"));
PrintWriterprintWriter=response.getWriter();
printWriter.print("客户端你好,数据连接成功!");
printWriter.flush();
printWriter.close();
}
request.getParameter(“变量名”)是用来接收客户端对应变量名的数据。
addressDao.insert()是我自己定义的方法,将接收到的数据存入MySQL中。
到此这篇关于Android服务端将位置信息发送给客户端的实现的文章就介绍到这了,更多相关Android服务端位置信息发送给客户端内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!