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是给多对父母和孩子使用的,而不是一对父母与孩子。

服务端也不应该是使用本地的,应该使用云服务器,这样就不会被同一局域网所限制。

Android 客户端将位置信息发送给服务端

代码实现

客户端:

 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 服务端将位置信息发送给客户端的实现的文章就介绍到这了,更多相关Android 服务端位置信息发送给客户端内容请搜索云海天教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持云海天教程!