Android 服务端中是如何将位置信息发送给客户端的?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
Android 服务端将位置信息发送给客户端
AndroidStudio Eclipse
服务端Servlet调用Dao层在数据库中查找数据,在servlet中将查找到的数据汇集成json字符串(json数组形式)。
服务端:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// response.setContentType("text/plain; charset=UTF-8");
request.setCharacterEncoding("UTF-8");
ServerToParentDao stpDao = new ServerToParentDao();
// String num = mtpDao.query();
// System.out.println(num);
PrintWriter out = response.getWriter();
StringBuffer sb = new StringBuffer();
sb.append('[');
List<Address> addrList = stpDao.queryOne();
for (Address address : 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("连接成功");
// PrintWriter printWriter = response.getWriter();
// printWriter.print("客户端你好,数据连接成功!");
// printWriter.flush();
// printWriter.close();
}
客户端:
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HttpPost httpRequest = new HttpPost("http://192.168.159.1:8080/MyAndroidServer/ServerToParentServlet");
List<NameValuePair> params = new ArrayList<NameValuePair>();
// String str = "1";
// params.add(new BasicNameValuePair("Code", str));
Log.i("MY3", "Has Done");
try {
// httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));//设置请求参数项
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpRequest);//执行请求返回响应
if (httpResponse.getStatusLine().getStatusCode() == 200) {//判断是否请求成功
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
System.out.println("---------");
// System.out.println("Respone content" + EntityUtils.toString(entity, "UTF-8"));
Intent intent = new Intent(ParentRequest.this,MainActivity.class);
intent.putExtra("jsonString",EntityUtils.toString(entity, "UTF-8"));
startActivity(intent);
}
Log.i("MY2", "Has Done");
} else {
Toast.makeText(ParentRequest.this, "没有获取到Android服务器端的响应!", Toast.LENGTH_LONG).show();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
请求地址书写形式:http://主机IP地址:端口号/项目名/action名
HttpPost方式建立连接,HttpResponse.getEntity()获取响应信息,EntityUtils.toString(entity, “UTF-8”)将entity转为String字符串,Intent将JSON字符串传递到其他activity页面中去。
JSON字符串解析类:
public static List<Address> getAddress(String jsonStr)
throws JSONException {
/******************* 解析 ***********************/
// 初始化list数组对象
List<Address> mList = new ArrayList<Address>();
Address address = new Address();
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
address = new Address(jsonObject.getInt("id"),
jsonObject.getString("latitude"), jsonObject.getString("longitude"),
jsonObject.getString("time"));
mList.add(address);
}
return mList;
}
我这个是当时在做一个儿童定位写的,数据库设计没思考全面,思维比较狭隘。
应该思考到的是儿童信息表中儿童信息要跟父母表中父母信息对应起来,即这APP是给多对父母和孩子使用的,而不是一对父母与孩子。
服务端也不应该是使用本地的,应该使用云服务器,这样就不会被同一局域网所限制。
代码实现
客户端:
HttpPost httpRequest = new HttpPost("http://192.168.159.1:8080/MyAndroidServer/ChildrenToServerServlet");
List<NameValuePair> params = new ArrayList<NameValuePair>();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
Date date = new Date(System.currentTimeMillis());
String str=simpleDateFormat.format(date);
System.out.println(str);
params.add(new BasicNameValuePair("Time", str));
params.add(new BasicNameValuePair("Latitude",latitude));
params.add(new BasicNameValuePair("Longitude", longitude));
try {
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));//设置请求参数项
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpRequest);//执行请求返回响应
if(httpResponse.getStatusLine().getStatusCode() == 200){//判断是否请求成功
// Toast.makeText(ChildrenToServerActivity.this, EntityUtils.toString(httpResponse.getEntity()), Toast.LENGTH_LONG).show();
Intent intent = new Intent();
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();
Intent intent = new Intent();
intent.setAction("cn.abel.action.broadcast");
intent.putExtra("Response", "没有获取到Android服务器端的响应!");
context.sendBroadcast(intent);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
params.add(new BasicNameValuePair(“Time”, str));
Time是str的变量名,用于服务端接收数据用的。
这是用来添加要传递给服务端的数据,为String字符串形式。
服务端:
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/plain; charset=UTF-8");
request.setCharacterEncoding("UTF-8");
String time = request.getParameter("Time");
String latitude = request.getParameter("Latitude");
String longitude = request.getParameter("Longitude");
ChildrenToAddressDao addressDao = new ChildrenToAddressDao();
addressDao.insert(latitude, longitude, time);
System.err.println(request.getParameter("Time"));
System.err.println(request.getParameter("Latitude"));
System.err.println(request.getParameter("Longitude"));
PrintWriter printWriter = response.getWriter();
printWriter.print("客户端你好,数据连接成功!");
printWriter.flush();
printWriter.close();
}
request.getParameter(“变量名”)是用来接收客户端对应变量名的数据。
addressDao.insert()是我自己定义的方法,将接收到的数据存入MySQL中。
看完上述内容,你们掌握Android 服务端中是如何将位置信息发送给客户端的的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。