其他分享
首页 > 其他分享> > Android 服务端将位置信息发送给客户端

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是给多对父母和孩子使用的,而不是一对父母与孩子。
服务端也不应该是使用本地的,应该使用云服务器,这样就不会被同一局域网所限制。

标签:address,发送给,服务端,sb,println,new,Android,append,out
来源: https://blog.csdn.net/weixin_43752257/article/details/112966877