一、題目
Android 客戶端將位置資訊發送給服務端
二、環境
Android Studio Eclipse
三、代碼實作
客戶端:
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服務端將位置資訊發送給客戶端
可以看這篇博客,
有問題,歡迎留言交流!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/251801.html
標籤:其他
上一篇:RK3399平臺開發系列講解(內核除錯篇)9.2、如何使用dump_stack分析函式呼叫關系
下一篇:學習日志13
