Android platform calls Web Service: Example

Source: Internet
Author: User
Tags dotnet

Recently, I am studying Android. With the popularity of mobile devices, when the software becomes commercially available, Android must be supported in order to compete for the market. So I started to get started with Android, but I only want to know about it, it is easier to manage because we need to be a manager and understand Android.

Android is also easy to learn and better encapsulated. Various controls seem to return to the catch-up of VB.

The following example shows how to call Web Service on the Android platform. We use the Internet ready-made Webservice for querying the Web service of the mobile phone number home location, its wsdl for the http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx? Wsdl.

1) Create an Android project, introduce the ksoap2-android class library downloaded above

Calling WebService on the Android platform depends on the third-party class library ksoap2. It is a SOAP Webservice client development kit, it is mainly used in Resource-restricted Java environments such as Applets or j2s applications (CLDC/CDC/MIDP ).

Instead of using ksoap2 directly on the Android platform, ksoap2android is used. KSoap2 Android is an efficient and lightweight SOAP development kit on the Android platform.

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

   
       
        
        
        
    
   


3) Compile the MainActivity class

/*** The Android platform calls WebService (mobile phone number retrieval) **/public class MainActivity extends Activity {private EditText phoneSecEditText; private TextView resultView; private Button queryButton; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); // force StrictMode operations in the UI thread. setThreadPolicy (newStrictMode. threadPolicy. builder (). detectDiskRead S (). detectDiskWrites (). 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 OnClickL Istener () {@ Override public void onClick (View v) {// mobile phone number (segment) String phoneSec = phoneSecEditText. getText (). toString (). trim (); // you can easily determine whether the entered mobile phone number (segment) is legal if ("". equals (phoneSec) | phoneSec. length () <7) {// error message: phoneSecEditText. setError ("the phone number (segment) You entered is incorrect! "); PhoneSecEditText. requestFocus (); // clears the resultView of the query result. setText (""); return ;}// query the mobile phone number (segment) Information getRemoteInfo (phoneSec );}});} /*** phone number segment attribution query ** @ param phoneSec phone number segment */public void getRemoteInfo (String phoneSec) {// nameSpace String nameSpace = "http://WebXml.com.cn /"; // call method name String methodName = "getMobileCodeInfo"; // EndPoint String endPoint = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx"; // SOAP Action String soapAction = "http://WebXml.com.cn/getMobileCodeInfo "; // specify the WebService nameSpace and method name SoapObject rpc = new SoapObject (nameSpace, methodName); // set the two parameters mobileCode and userId rpc to be passed in to call the WebService interface. addProperty ("mobileCode", phoneSec); rpc. addProperty ("userId", ""); // generate the SOAP request information that calls the WebService method, and specify the SOAP version SoapSerializationEnvelope envelope = new SoapSerializationEnvelope (SoapEnvelope. VER10); envelope. bodyOut = rpc; // you can specify whether to call the WebService envelope developed by dotNet. 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 ();} // obtain the returned data SoapObject object = (SoapObject) envelope. bodyIn; // obtain the returned result String result = object. getProperty (0 ). toString (); // display the results returned by WebService in resultView. setText (result );}}


Notes1:NameSpace, methodName, EndPoint, and SOAP Action information can be obtained in WSDL.

Notes2:When the WebService interface method is called, the parameter name must be the same as that described in the WSDL. (Some information on the internet says that when multiple parameters need to be input, the order of multiple parameters is as follows:WSDLThe order of the parameters in is the same, and the name does not need to be the sameWSDLBut the actual test shows that it is not feasible in most cases!)

Notes3:In this example, the results returned after WebService is called are as follows:

1398547 : Guizhou Guiyang Guizhou mobile and Guizhou middleware card

Here the returned content is in xml format. Why don't we need to parse the xml to get the content we need? Actually:

// Obtain the returned data

SoapObject object = (SoapObject) envelope. bodyIn;

Ksoap2 can convert the returned xml into a SoapObject object, and then we can obtain the required data by operating on the object.

Notes4:In this example, only one value is returned, but some WebServices return multiple values. How can this problem be obtained? The method for obtaining the object is exactly the same as in this example. It is worth noting that if multiple values are returned, the result may still be a SoapObject through the 100th code object. getProperty (0. Call the getProperty () method constantly; always get all the results you want.

4) configure the network access permission in AndroidManifest. xml.

   
                               
                                      
                 
                         
         
        
     
   

5) running result

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.