Android:客户端通过HTTP连接服务器,完成注册并传送坐标信息
来源:互联网 发布:et服装软件免费下载 编辑:程序博客网 时间:2024/06/17 23:23
一、Main.xml
主要是2个Button和一个TextView。“设备注册”点击后即向服务器发送设备的MAC、HolderName等信息;“坐标传送”则输送设备从iBeacon获取的坐标信息到服务器,经过定位算法处理后再从服务器传回修正坐标信息(因篇幅有限,本节暂不提坐标信息是如何获取的)。下面的TextView用于实时显示状态信息。其他的View主要用于实际调试。
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"><LinearLayout android:orientation="horizontal" android:layout_width="fill_parent"android:layout_height="wrap_content" android:layout_marginTop="10dp"><TextView android:layout_width="wrap_content"android:layout_height="wrap_content" android:text="信息交互窗口" android:textSize="16dp"android:layout_marginRight="10dp" /><EditText android:id="@+id/tvEdit" android:layout_width="fill_parent" android:text=""android:layout_height="wrap_content" /></LinearLayout><Button android:id="@+id/btnGetQuery" android:layout_width="fill_parent"android:layout_height="wrap_content" android:text="设备注册" /><Button android:id="@+id/btnPostQuery" android:layout_width="fill_parent"android:layout_height="wrap_content" android:text="坐标传送" /><TextView android:id="@+id/tvQueryResult"android:layout_width="fill_parent" android:layout_height="wrap_content" /></LinearLayout>
二、建立HTTP连接
1、NetworkService类用于建立HTTP连接。
2、url_ip为服务器IP地址,
getPostResult()方法传入的url为服务器定义的action,本文为"equipment_Register_VIPRegister_n.action"
package net.blogjava.mobile;import java.io.UnsupportedEncodingException;import java.util.List;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.params.BasicHttpParams;import org.apache.http.params.HttpConnectionParams;import org.apache.http.util.EntityUtils;import android.util.Log;public class NetworkService {private static String TAG = "NetworkService";//private static String url_ip = ServerUrl.SERVER_ADRESS+"UserInfoServlet?";private static String url_ip = "http://192.168.1.231:8080/indoor/";/** * 释放资源 */public static void cancel() {Log.i(TAG, "cancel!");// if(conn != null) {// conn.cancel();// }}//无参数传递的public static String getPostResult(String url){url = url_ip + url;//创建http请求对象HttpPost post = new HttpPost(url);//创建HttpParams以用来设置HTTP参数 BasicHttpParams httpParams = new BasicHttpParams();HttpConnectionParams.setConnectionTimeout(httpParams,10 * 1000);HttpConnectionParams.setSoTimeout(httpParams, 10 * 1000);//创建网络访问处理对象HttpClient httpClient = new DefaultHttpClient(httpParams);try{//执行请求参数�?HttpResponse response = httpClient.execute(post);//判断是否请求成功if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {//获得响应信息String content = EntityUtils.toString(response.getEntity());return content;} else {//网连接失败,使用Toast显示提示信息}}catch(Exception e) {e.printStackTrace();return "{\"status\":405,\"resultMsg\":\"网络超时!\"}";} finally {//释放网络连接资源httpClient.getConnectionManager().shutdown();}return "{\"status\":405,\"resultMsg\":\"网络超时!\"}";} //有参数传递的public static String getPostResult(String url, List<NameValuePair> paramList){UrlEncodedFormEntity entity = null;try {entity = new UrlEncodedFormEntity(paramList,"utf-8");} catch (UnsupportedEncodingException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}//创建http请求对象HttpPost post = new HttpPost(url);BasicHttpParams httpParams = new BasicHttpParams();HttpConnectionParams.setConnectionTimeout(httpParams, 10 * 1000);HttpConnectionParams.setSoTimeout(httpParams, 10 * 1000);post.setEntity(entity);//创建网络访问处理对象HttpClient httpClient = new DefaultHttpClient(httpParams);try{//执行请求参数�?HttpResponse response = httpClient.execute(post);//判断是否请求成功if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {//获得响应信息String content = EntityUtils.toString(response.getEntity(),"UTF-8");return content;} else {//网连接失败,使用Toast显示提示信息}}catch(Exception e) {e.printStackTrace();return "{\"status\":405,\"resultMsg\":\"网络超时!\"}";} finally {//释放网络连接资源httpClient.getConnectionManager().shutdown();}return "{\"status\":405,\"resultMsg\":\"网络超时!\"}";}}
三、注册信息的传送
1、定义List<NameValuePair>:
List<NameValuePair> paramList = new ArrayList<NameValuePair>();paramList.add(new BasicNameValuePair("headTage","device"));paramList.add(new BasicNameValuePair("idmac",IDMAC));paramList.add(new BasicNameValuePair("model",MODEL));paramList.add(new BasicNameValuePair("holdername",HOLDERNAME));
2、调用NetworkService类里面的getPostResult()方法:
String str ="";str = NetworkService.getPostResult(url, paramList);
3、Json解析服务器回馈的信息
(需自行下载并添加json的包)
import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import org.json.JSONTokener;
try {JSONTokener jsonParser = new JSONTokener(result);JSONObject responseobj = (JSONObject) jsonParser.nextValue(); if("failed".equals(responseobj.getString("errorMsg"))){tvQueryResult.setText(responseobj.getString("resul"));//closeHeaderOrFooter(true);}else{<pre name="code" class="java"> tvQueryResult.setText("没有数据");}else {<pre name="code" class="java"><pre name="code" class="java"> tvQueryResult.setText("数据获取失败");}} catch (Exception e) {<pre name="code" class="java"><pre name="code" class="java"><pre name="code" class="java"><pre name="code" class="java"> tvQueryResult.setText("数据获取失败");}3、因http耗时需将设备注册与左边信息传送放在异步线程里来执行,否则会报异常
//注册 class RegisterAsyncTask extends AsyncTask<String, Integer, String> { Context myContext; TextView tvQueryResult = (TextView) findViewById(R.id.tvQueryResult); public RegisterAsyncTask(Context context) { myContext = context; } @Override protected String doInBackground(String... params) { // TODO Auto-generated method stub try { resultData = InitData(); Thread.sleep(1000); } catch (Exception e) { } return resultData; } @Override protected void onPreExecute() { } protected String InitData() { String IDMAC=getLocalMacAddress(); String MODEL = android.os.Build.MODEL==null ?"未知":android.os.Build.MODEL; String HOLDERNAME = android.os.Build.USER==null ?"未知":android.os.Build.USER; String str =""; String url = "http://192.168.1.226:8080/indoor/equipment_Register_VIPRegister_n.action"; List<NameValuePair> paramList = new ArrayList<NameValuePair>(); paramList.add(new BasicNameValuePair("headTage","device")); paramList.add(new BasicNameValuePair("idmac",IDMAC)); paramList.add(new BasicNameValuePair("model",MODEL)); paramList.add(new BasicNameValuePair("holdername",HOLDERNAME)); str = NetworkService.getPostResult(url, paramList); Log.i("msg", str); return str; } protected void onPostExecute(String result) { try { JSONTokener jsonParser = new JSONTokener(result); JSONObject responseobj = (JSONObject) jsonParser.nextValue(); if("failed".equals(responseobj.getString("errorMsg"))) { tvQueryResult.setText(responseobj.getString("resul")); } else { tvQueryResult.setText("数据获取失败"); } } catch (Exception e) { tvQueryResult.setText("数据获取失败"); } } }
四、主程序
package net.blogjava.mobile;import java.util.ArrayList;import java.util.List;import org.json.JSONArray;import org.json.JSONObject;import org.json.JSONTokener;import org.apache.http.NameValuePair;import org.apache.http.message.BasicNameValuePair;import net.blogjava.mobile.NetworkService;import com.pojo.DeviceInfo;import com.pojo.PositionInput;import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;import android.net.wifi.WifiInfo;import android.net.wifi.WifiManager;import android.content.Context; public class Main extends Activity implements OnClickListener{private String resultData;DeviceInfo device =new DeviceInfo();@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);Button btnGetQuery = (Button) findViewById(R.id.btnGetQuery);Button btnPostQuery = (Button) findViewById(R.id.btnPostQuery);btnGetQuery.setOnClickListener(this);btnPostQuery.setOnClickListener(this); RegisterDevice();}@Overridepublic void onClick(View view){//String url = "";TextView tvQueryResult = (TextView) findViewById(R.id.tvQueryResult);/*HttpResponse httpResponse = null;*/try{switch (view.getId()){case R.id.btnGetQuery:tvQueryResult.setText("正在注册...");RegisterDevice();break;case R.id.btnPostQuery:tvQueryResult.setText("传送坐标信息...");PositionPost();break;}}catch (Exception e){tvQueryResult.setText(e.getMessage());}}//注册按钮执行事件protected void RegisterDevice(){//Toast.makeText(Main.this,"注册中...", 1000).show();//new AlertDialog.Builder(Main.this).setMessage("正在注册...").create().show();RegisterAsyncTask Register = new RegisterAsyncTask(this); Register.execute("");//new AlertDialog.Builder(Main.this).setMessage("注册成功").create().show();}//坐标传送按钮执行事件protected void PositionPost(){PositionPostAsyncTask PositionPost = new PositionPostAsyncTask(this);PositionPost.execute("");};//注册class RegisterAsyncTask extends AsyncTask<String, Integer, String> {Context myContext;TextView tvQueryResult = (TextView) findViewById(R.id.tvQueryResult);public RegisterAsyncTask(Context context) {myContext = context;}@Overrideprotected String doInBackground(String... params) {// TODO Auto-generated method stubtry {resultData = InitData();Thread.sleep(1000); } catch (Exception e) {}return resultData;}@Overrideprotected void onPreExecute() {} protected String InitData() {String IDMAC=getLocalMacAddress();String MODEL = android.os.Build.MODEL==null ?"未知":android.os.Build.MODEL;String HOLDERNAME = android.os.Build.USER==null ?"未知":android.os.Build.USER;String str ="";String url = "http://192.168.1.226:8080/indoor/equipment_Register_VIPRegister_n.action";List<NameValuePair> paramList = new ArrayList<NameValuePair>();paramList.add(new BasicNameValuePair("headTage","device"));paramList.add(new BasicNameValuePair("idmac",IDMAC));paramList.add(new BasicNameValuePair("model",MODEL));paramList.add(new BasicNameValuePair("holdername",HOLDERNAME));str = NetworkService.getPostResult(url, paramList);Log.i("msg", str);return str;}protected void onPostExecute(String result) {try {JSONTokener jsonParser = new JSONTokener(result);JSONObject responseobj = (JSONObject) jsonParser.nextValue(); if("failed".equals(responseobj.getString("errorMsg"))){tvQueryResult.setText(responseobj.getString("resul"));}else {tvQueryResult.setText("数据获取失败");}} catch (Exception e) { tvQueryResult.setText("数据获取失败");}}}//位置坐标传送class PositionPostAsyncTask extends AsyncTask<String, Integer, String> {Context myContext;public PositionPostAsyncTask(Context context) {myContext = context;}@Overrideprotected String doInBackground(String... params) {// TODO Auto-generated method stubtry {resultData = InitData();Thread.sleep(1000); } catch (Exception e) {}return resultData;}@Overrideprotected void onPreExecute() {} protected String InitData() { PositionInput position=new PositionInput(); String str ="";String url = "equipment_Register_VIPRegister_n.action";List<NameValuePair> paramList = new ArrayList<NameValuePair>();paramList.add(new BasicNameValuePair("headTage","position"));paramList.add(new BasicNameValuePair("x",String.valueOf(position.getX())));paramList.add(new BasicNameValuePair("y",String.valueOf(position.getY())));paramList.add(new BasicNameValuePair("z",String.valueOf(position.getZ())));str = NetworkService.getPostResult(url, paramList);Log.i("msg", str);return str;}protected void onPostExecute(String result) {try {JSONTokener jsonParser = new JSONTokener(result);JSONObject responseobj = (JSONObject) jsonParser.nextValue(); if("position".equals(responseobj.getString("headTage"))){JSONArray neworderlist = responseobj.getJSONArray("response");int length = neworderlist.length();if (length > 0) {for(int i = 0; i < length; i++){//遍历JSONArrayJSONObject jo = neworderlist.getJSONObject(i);//解析为坐标信息float x = Float.parseFloat(jo.getString("x"));float y = Float.parseFloat(jo.getString("y"));float z = Float.parseFloat(jo.getString("z")); }}else{}}else {}} catch (Exception e) {}}}public String getLocalMacAddress() { WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiInfo info = wifi.getConnectionInfo(); return info.getMacAddress(); }}
0 0
- Android:客户端通过HTTP连接服务器,完成注册并传送坐标信息
- Android通过Http连接MySQL 实现登陆/注册(数据库+服务器+客户端),android+mysql
- Android通过Http连接MySQL 实现登陆/注册(数据库+服务器+客户端)
- Android通过Http连接MySQL 实现登陆/注册(数据库+服务器+客户端)
- Android通过Http连接MySQL 实现登陆/注册(数据库+服务器+客户端)
- Android通过Http连接MySQL 实现登陆/注册(数据库+服务器+客户端),androidmysql
- Android通过Servlet连接MySQL 实现登陆/注册(数据库+服务器+客户端)
- Android客户端通过Socket连接服务器
- android 通过socket连接服务器与客户端
- Android客户端通过Socket连接服务器
- Android通过Http连接MySQL 实现登陆/注册(数据库+service+客户端)【大部分转自帮客之家】
- 通过SecureCRT SSH远程连接服务器并使用Zmodem传送文件
- java客户端仿http传送文件到php服务器
- HTTP服务器可以响应POST请求,并能响应注册信息
- 通过httpclient向服务器传送数据并获得返回值
- android http连接服务器
- android上客户端到服务端通过Entity传送数据
- 通过servlet连接数据库和HTML,完成登陆注册
- 状态DP
- oracle数据库的备份及升级
- 通俗易懂解释java反射机制(二)
- toggle2
- nike耐克真的用上了昊金线业的缝纫线?
- Android:客户端通过HTTP连接服务器,完成注册并传送坐标信息
- 与百度合作的这几个月的总结
- MySQL临时表
- CentOS 7 正式版发布及下载地址
- 三:1.cp + inotify + NFS 实现即时备份shell
- 清除Eclipse工作空间列表
- IIS---并发数
- 安装centos共享文件夹
- C++ 函数