Android:用戶端通過HTTP串連伺服器,完成註冊並傳送座標資訊

來源:互聯網
上載者:User

標籤:android   用戶端   伺服器   註冊   座標   

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




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.