Android platform invoke Web Service: Demo sample

Source: Internet
Author: User
Tags dotnet

recently in the study Android , with the popularity of mobile devices, when software on the road to commercialization, in order to compete for the market, must support Android , so it started to touch the Android , just understand the fur just fine, because we want to be a manager, understand Point Android , easy to manage.

Android It's also easy to learn, packaged better, and a control that looks like it's back VB the bright.

The following is a demonstration example of how to invoke a Web Service on an Android platform. We use the Internet ready- made Webservicefor querying the Web serviceof the mobile phone number attribution , its WSDL is http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl .

1) New Androidproject, introducing the Ksoap2-android class library downloaded above

Calling WebService on the Android platform relies on third-party class library KSOAP2, a SOAP webserviceclient development package, primarily for resource-constrained Java environments such as applets or J2ME applications (cldc/cdc/ MIDP).

and We do not use KSOAP2 directly on the Android platform, but instead use ksoap2android. KSoap2 Android is an efficient, lightweight soap development package on the Android platform

2) write the layout file Res/layout/main.xml

<?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_pare NT "android:paddingtop=" 5dip "android:paddingleft=" 5dip "android:paddingright=" 5dip "> <tex TView android:layout_width= "fill_parent" android:layout_height= "wrap_content" android:text= "hand Machine number (segment): "/> <edittext android:id=" @+id/phone_sec "android:layout_width=" Fill_parent "and roid:layout_height= "Wrap_content" android:inputtype= "Textphonetic" android:singleline= "true" an Droid:hint= "such as: 1398547"/> <button android:id= "@+id/query_btn" android:layout_width= "wrap_content "Android:layout_height=" wrap_content "android:layout_gravity=" right "android:text=" query "/&      Gt <textview android:id="@+id/result_text" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" a   ndroid:layout_gravity= "Center_horizontal|center_vertical"/> </LinearLayout>


3) Writing Mainactivity class

/** * Android Platform call WebService (mobile number Attribution query) * */public class Mainactivity extends Activity {private EditText phones      Ecedittext;      Private TextView Resultview;        Private Button Querybutton;          @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);    Setcontentview (R.layout.main); Forces operations on the UI thread Strictmode.setthreadpolicy (NewStrictMode.ThreadPolicy.Builder (). Detectdiskreads (). Detectdis                   Kwrites (). Detectnetwork (). Penaltylog (). build ()); Strictmode.setvmpolicy (NewStrictMode.VmPolicy.Builder (). Detectleakedsqlliteobjects (). Penaltylog (). Penaltydeath         (). Build ());          Phonesecedittext = (EditText) Findviewbyid (R.ID.PHONE_SEC);          Resultview = (TextView) Findviewbyid (R.id.result_text);            Querybutton = (Button) Findviewbyid (R.ID.QUERY_BTN); Querybutton.setonclicklistener (New Onclicklistener () {@Override publicvoid OnClick (View v) {//Mobile number (segment) String phonesec = Phonesecedittext.gettext (). ToString (                  ). Trim (); Simply infer whether the mobile number (segment) entered by the user is legal if ("". Equals (phonesec) | | Phonesec.length () < 7) {//Give error Phonesecedittext.seterror ("You entered the mobile number (segment) is wrong!                      ");                      Phonesecedittext.requestfocus ();                      The TextView that displays the results of the query is emptied Resultview.settext ("");                  Return              }//Query mobile number (segment) Information getremoteinfo (PHONESEC);      }          }); }/** * Mobile number Segment Attribution Query * * @param phonesec Mobile phone number segment */public void Getremoteinfo (String phonesec)          {//namespace String nameSpace = "http://WebXml.com.cn/";          The method name called String methodName = "Getmobilecodeinfo"; EndPoint String EndPoint = "Http://webservice.webxml.com.cn/WebServices/MobiLecodews.asmx ";            SOAP Action String soapaction = "Http://WebXml.com.cn/getMobileCodeInfo";            Specifies the namespace of the WebService and the method name called Soapobject RPC = new Soapobject (NameSpace, methodName);          Set the two Mobilecode, UserId rpc.addproperty ("Mobilecode", phonesec) that need to be passed in to call the WebService interface;            Rpc.addproperty ("UserId", ""); Generates a SOAP request message that calls the WebService method and specifies the version number of soap Soapserializationenvelope envelope = new Soapserializationenvelope (soape Nvelope.            VER10);          Envelope.bodyout = RPC;          Sets whether to invoke the DotNet developed webservice envelope.dotnet = true;          Equivalent to envelope.bodyout = RPC;            Envelope.setoutputsoapobject (RPC);          Httptransportse transport = new Httptransportse (endPoint);          try {//Call WebService Transport.call (SOAPAction, envelope);          } catch (Exception e) {e.printstacktrace (); }//Gets the returned data soapobject object = (soApobject) Envelope.bodyin;            Gets the result returned by String result = Object.getproperty (0). toString ();      The results returned by WebService are displayed in TextView resultview.settext (result);   }  }


      watch out.1:NamespAce,MethodName,EndPointand theSOAP Action information, you canWSDLobtained in the.

      watch out.2:calledWebServicewhen an interface method requires an incoming argument, the name of theWSDLthe description of the narrative in the same. (Some of the information on the web says that in order to pass in multiple parameters, only a number ofWSDLin the order in which the parameters appear, the names do not need to beWSDL, but the actual test found that most of the cases are not feasible! )

Note Point 3: In this example, call WebService The results that are returned after this are as follows:

<?xml version= "1.0" encoding= "Utf-8"?>

            <stringxmlns="http://WebXml.com.cn/">1398547: GuizhouGuiyangGuizhou Mobile Qian mid -stream card</string>

This is what is clearly returned in the XML format, why don't we need to parse the XML to get what we need? In fact:

// Get the returned data

Soapobject object = (soapobject) Envelope.bodyin;

KSOAP2 can convert the returned XML into a Soapobject object, and then we get the data we need by manipulating the object.

     watch out.4:in this case, only one value is returned, but someWebServicewill return more than one value how to get it? The Fetch method is exactly the same as in this case, and it is only necessary to note that the assumption is to return multiple values through the -Codeobject.getproperty (0);the resulting may still be aSoapobject. Constantly callingGetProperty ()always get all the results you want.

4) Configure permissions to join the access network in Androidmanifest.xml

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android= "http://schemas.android.com/apk/res/      Android "package=" Com.liufeng.ws.activity "android:versioncode=" 1 "android:versionname=" 1.0 "> <application android:icon= "@drawable/icon" android:label= "@string/app_name" > <activity android:name= ". M Ainactivity "android:label=" @string/app_name "> <intent-filter> <action android:n               Ame= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> <uses-sdk ANDROID:MINSD   kversion= "4"/> <!--access Network permissions--<uses-permission android:name= "Android.permission.INTERNET"/> </manifest>

5) Execution Results


Source code Download

http://download.csdn.net/detail/tcl_6666/7365311

Related Article

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.