Android platform invoke Web Service: Example

Source: Internet
Author: User
Tags dotnet soap wsdl

recently in the study Android , with the popularity of mobile devices, when the software on the road to commercialization, in order to compete for the market, there must be support Android , so I started to get in touch. Android , but only to understand the fur is good, because we want to be a manager, understand the point Android , easier to manage.

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

Here's an example of how to invoke a Web Service on the 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 Android project, introducing the Ksoap2-android class library downloaded above

Calling WebService on the Android platform relies on a third-party class library KSOAP2, which is a SOAP WebService client 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= "For example: 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 (); Simple to determine whether the user entered the mobile phone number (segment) 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 parameters Mobilecode, UserId rpc.addproperty ("Mobilecode", phonesec) that need to be passed in to call the WebService interface;            Rpc.addproperty ("UserId", ""); Generates the SOAP request information that calls the WebService method and specifies the version of soap Soapserializationenvelope envelope = new Soapserializationenvelope (soapen Velope.            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 parameter, the parameter name isWSDLthe same as described in. (Some of the information on the web says that when multiple parameters need to be passed in, the order of multiple parametersWSDLin the same 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: The result returned after calling WebService in this example is 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 is able to convert the returned XML into a Soapobject object, and then we can get the data we need by manipulating the object.

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

4) Configure the Add access to the 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 to the network and <uses-permission android:name= "Android.permission.INTERNET"/> </manifest>

5) Running Results


SOURCE download

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

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.