Android: Client connects to server via HTTP, completes registration and transmits coordinate information

Source: Internet
Author: User

First, Main.xml

It is mainly 2 button and one textview. "Device Registration" after clicking on the server to send the device's Mac, holdername and other information; "Coordinate transfer" the transfer equipment from the ibeacon obtained from the coordinate information to the server, after the location algorithm processing and then back from the server to correct the coordinate information (due to limited space, This section temporarily does not mention how the coordinate information is obtained. The following textview are used to display status information in real time. Other view is mainly used for actual debugging.

<?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= "Information interaction window" 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= "Device Registration"/><button android:id= "@+id/btnpostquery" Android: Layout_width= "Fill_parent" android:layout_height= "wrap_content" android:text= "coordinate transfer"/><textview android:id= " @+Id/tvqueryresult "android:layout_width=" fill_parent "android:layout_height=" Wrap_content "/></LinearLayout >

Second, establish an HTTP connection

1. The NetworkService class is used to establish an HTTP connection.

2, URL_IP is the server IP address,

Getpostresult () method The URL passed in is the server-defined action, this article is "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/";/** * Frees resource */public static void Cancel () {log.i (TAG, "C Ancel! "); /IF (conn! = null) {//Conn.cancel ();//}}//no parameter passed public static string Getpostresult (string url) {url = url_ip + url;//Create HT TP Request Object HttpPost post = new HttpPost (URL);//Create Httpparams to set the HTTP parameter basichttpparams httpparams = new Basichttpparams (); Httpconnectionparams.setconnectiontimeout (httpparams,10 * 1000); Httpconnectionparams.setsotimeout (Httpparams, 10 * 1000);//Create a Network Access processing object httpClient httpClient = new Defaulthttpclient ( Httpparams); try{//execute request parameter?? HttpResponse response = Httpclient.execute (post);//Determine if the request succeeds if (Response.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {//Get response information string content = Entityutils.tostring (response.getentity ()); return content;} else {//NET connection failed , use toast to display hint information}}catch (Exception e) {e.printstacktrace (); return "{\" status\ ": 405,\" resultmsg\ ": \" Network timeout! \"}";} finally {//Releases network connection resource Httpclient.getconnectionmanager (). shutdown ();} Return "{\" status\ ": 405,\" resultmsg\ ": \" Network timeout!   \"}";} public static string Getpostresult (string url, list<namevaluepair> paramlist) with parameters passed {urlencodedformentity entity = null;try {entity = new urlencodedformentity (paramlist, "Utf-8");} catch (Unsupportedencodingexception E1) {//TOD O auto-generated Catch Blocke1.printstacktrace ();} Create an HTTP request object HttpPost post = new HttpPost (URL); Basichttpparams httpparams = new Basichttpparams (); Httpconnectionparams.setconnectiontimeout (Httpparams, 10 * 1000); Httpconnectionparams.setsotimeout (httpparams);p ost.setentity (entity);//Create a Network Access processing object HttpClient httpClient = New Defaulthttpclient (httpparams); try{//execute request parameter?? HttpResponse response = Httpclient.execute (post);//Determine if the request succeeds if (Response.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {//Get response information string content = Entityutils.tostring (response.getentity (), "UTF-8"); return content;} else {//NET connection failed, display prompt with Toast}} catch (Exception e) {e.printstacktrace (); return "{\" status\ ": 405,\" resultmsg\ ": \" Network timeout! \"}";} finally {//Releases network connection resource Httpclient.getconnectionmanager (). shutdown ();} Return "{\" status\ ": 405,\" resultmsg\ ": \" Network timeout! \"}";}}

Third, the transfer of registration information

1, definition list<namevaluepair>:

list<namevaluepair> paramlist = new arraylist<namevaluepair> ();p Aramlist.add (New BasicNameValuePair (" Headtage "," Device ");p Aramlist.add (New Basicnamevaluepair (" Idmac ", Idmac));p Aramlist.add (New Basicnamevaluepair (" Model);p Aramlist.add (New Basicnamevaluepair ("Holdername", Holdername));

2. Call the Getpostresult () method inside the NetworkService class:

String str = ""; str = networkservice.getpostresult (URL, paramlist);

3, JSON parsing server feedback information

(You need to download and add the JSON package yourself)

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 ("no Data");} else {<pre name= "code" class= "java" ><pre name= "code" class= "java" >                                 tvqueryresult.settext ("Data acquisition Failed");}} 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 ("Data acquisition Failed");}

3, because the HTTP time-consuming device registration and the left side of the information transfer in the asynchronous thread to execute, otherwise it will report an exception


Registration     class RegisterAsyncTask extends Asynctask<string, Integer, string> {    & nbsp;   context mycontext;        textview tvqueryresult = (TextView) Findviewbyid (r.id.tvqueryresult);        public RegisterAsyncTask (context context) {             mycontext = context;        }& nbsp;        @Override         protected String doinbackground ( String ... params) {            //TODO auto-generated method stub & nbsp          try {                 resultdata = InitData ();                 Thread.Sleep (1000);             } catch (Exception e) {            }        & nbsp;   return resultdata;        }        @ override        protected void OnPreExecute () {        }& nbsp;      protected String initdata () {             String idmac=getlocalmacaddress ();            string MODEL = Android.os.build.model==null? " Unknown ":android.os.build.model;            string holdername = Android.os.build.user==null? " Unknown ":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 ("Data acquisition failed");         }        } catch (Exception e) {                 tvqueryresult.settext ("Data acquisition failed");        }    }        }

Iv. Main Program

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 ("Registering ..."); Registerdevice (); Break;case R.id.btnpostquery:tvqueryresult.settext ("Transmit coordinate information ..."); Positionpost (); break;}} catch (Exception e) {tvqueryresult.settext (E.getmessage ());}} The Register button executes the event protected void Registerdevice () {//toast.maketext (Main.this, "Registering ..."). Show ();//new Alertdialog.builder (main.this). Setmessage ("Registering ..."). Create (). Show ();    RegisterAsyncTask Register = new RegisterAsyncTask (this); Register.execute ("");//new Alertdialog.builder (Main.this). Setmessage ("registered successfully"). Create (). Show (); The coordinate Transfer button executes the event protected void Positionpost () {Positionpostasynctask positionpost = new Positionpostasynctask (this); Positionpost.eXecute ("");};/ /Register class RegisterAsyncTask extends Asynctask<string, Integer, string> {Context mycontext; TextView Tvqueryresult = (TextView) Findviewbyid (r.id.tvqueryresult);p ublic 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? " Unknown ": Android.os.Build.MODEL; String holdername = android.os.build.user==null? " Unknown ": 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> ();p Aramlist.add (New BasicNameValuePair (" Headtage "," Device "));p Aramlist.add (New Basicnamevaluepair (" Idmac ", Idmac));p Aramlist.add (New BasicnamEvaluepair ("model", model));p Aramlist.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 ("Data acquisition Failed");}} catch (Exception e) {tvqueryresult.settext ("Data acquisition Failed");}}} Location coordinates transfer 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> ();p Aramlist.add (New BasicNameValuePair (" Headtage "," position "));p Aramlist.add (New Basicnamevaluepair (" X ", String.valueof (Position.getx ())));p Aramlist.add (New Basicnamevaluepair ("Y", string.valueof (Position.gety ())));p Aramlist.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++) {//Traversal Jsonarrayjsonobje CT Jo = Neworderlist.getjsonobject (i);//parse to coordinate information 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) g      Etsystemservice (Context.wifi_service);    Wifiinfo info = Wifi.getconnectioninfo ();  return info.getmacaddress (); }}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.