Android server sends location information to client

One, the problem

Android server sends location information to client

2. Environment

AndroidStudio Eclipse

Three, code implementation

The server-side servlet calls the Dao layer to find data in the database, and integrates the found data into a json string (json array format) in the servlet.

Server:

	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();
	}

Client:

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();
                }
            }
        });

Request address writing format: http://host IP address: port number/project name/action name
HttpPost method to establish a connection, HttpResponse.getEntity() to obtain the response information, EntityUtils.toString(entity, "UTF-8") to convert the entity As a String string, the Intent will pass the JSON string to other activity pages.


JSON string parsing class:

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;
    }

I was writing this as a child positioning at the time. The database design was not comprehensive, and the thinking was rather narrow.
What should be considered is that the child information in the child information table should correspond to the parent information in the parent table, that is, this APP is for multiple pairs of parents and children, not a pair of parents and children.
The server should not use the local server, it should use the cloud server, so that it will not be restricted by the same LAN.

The Android client sends location information to the server.
Please see this article.

If you have any questions, please leave a message to exchange!

Guess you like

Origin blog.csdn.net/weixin_43752257/article/details/112966877