Android calls WebService (. NET platform)

Source: Internet
Author: User
Tags dotnet soap wsdl

What is WebService?

Web Service is a platform-independent, low-coupling, self-contained, programmable Web-based application that uses Open XML (a subset of standard common markup languages) to describe, publish, discover, orchestrate, and configure these applications for the development of distributed, interoperable applications. Web Service uses uniform, open standards on the Internet, such as HTTP, XML, SOAP (Simple Object Access Protocol), WSDL (WebService Description Language), and so on, so the web The service can be used in any environment that supports these standards (WINDOWS,LINUX). (plainly, WebService is like a method, but not written by yourself, but cross-lingual and cross-platform.) We just need to call this method to get the return result. As to how the WebService works is irrelevant to the caller and does not need to know)

Note: The SOAP protocol, Simple Object access Protocal, is an XML-based communication protocol for network information exchange in decentralized and distributed environments. Under this protocol, software components or applications can communicate through the standard HTTP protocol. It is designed to be simple and extensible, which facilitates interoperability between heterogeneous programs and platforms, so that existing applications can be accessed by a wide range of users.

Why use WebService?

Convenient and open. As we all know, the CPU and memory on the mobile phone is very limited, especially to deal with some big data and other easy-to-wear resources such as the operation will be very difficult or even impossible. Therefore, this part of the processing to the server side, let the server to process the data. Then on the server side we can implement a WebService let's call it on the client and return the data we need.

When do I use WebService?

as long as the data exchange can be used. but have to know the merits of WebService:

Advantages:

    1. Cross-platform, cross-language;
    2. The SOAP protocol is based on the industry standards of XML and HTTP, and is supported by all important companies.
    3. Because soap is used, the data is transmitted in ASCII text rather than binary, debugging is convenient, and because of this, its data is easy to pass through the firewall, do not need a firewall in order to open a separate "vulnerability."
    4. WebService is much less technically difficult to implement than CORBA and DCOM.
    5. To achieve business-to-business integration, EDI is more sophisticated and more complex, while the use of webservice can be low-cost implementation, small companies can also be used.
    6. In the C/S program, WebService can achieve the Web page without the overall refresh of dealing with the server and take the number.

Disadvantages:

    1. WebService uses XML to encapsulate data, which can result in large amounts of data being transmitted over the network.
    2. The WebService specification does not specify any implementation-related details, including the object model, programming language, which is less than CORBA.

How to use WebService? (The whole process is illustrated with an example of getting a cell phone number attribution)

To use WebService, you must know the interface documentation for WebService, which is the WSDL (WebService Description service). So what exactly does the WSDL look like?

Below I give a link: (The link opens is a WSDL)

http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl

After opening as shown: (not shown full)

Everyone looked at the dumbfounded, how much information, in the end what we need it?

In fact, we only need three data to call WebService: namespace, method name (including method name and parameter type), root node.

So where is the corresponding data on the WSDL?

The root node is the link given above to remove the "? wsdl": Http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx

namespaces, method names (including method names and parameter types) are in order from top to bottom, from left to right.

All right, I got this. So we can start working on it.

First, we need to download a Ksoap2jar package, which is the tool class we call WebService, which gives a: http://download.csdn.net/detail/af74776/7735251

Download the jar package and import it into the project (copy to the Libs folder, click the Jar package, right-click, select Build Path, and then select Add xxxxx (remember what is behind). Then, click Project, right-click, select Build Path, and then select Configure Build Pathxxxxx. On the right side of the popup dialog box, select the Order and Export tab. Tick the KSOAP2 jar package you just added, then select OK)

As follows:

Once the package is successfully imported, you can start writing code (EH, go directly to the code.) Detailed comments on the code):

Layout file Main.xml:

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent"android:orientation= "vertical"Android:paddingleft= "5dip"Android:paddingright= "5dip"Android:paddingtop= "5dip" >    <TextViewAndroid:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Mobile number (segment):" />    <EditTextAndroid:id= "@+id/phone_sec"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:hint= "For example: 1398547"Android:inputtype= "Textphonetic"Android:singleline= "true" />    <ButtonAndroid:id= "@+id/query_btn"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:layout_gravity= "Right"Android:text= "Query" />    <TextViewAndroid:id= "@+id/result_text"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:layout_gravity= "Center_horizontal|center_vertical" /></LinearLayout>
View Code

Mainactivity.java:

 Public classMainactivityextendsActivity {PrivateEditText Phonesecedittext; PrivateTextView Resultview; PrivateButton Querybutton;    String result; PrivateString phonesec; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.main); Phonesecedittext=(EditText) Findviewbyid (R.ID.PHONE_SEC); Resultview=(TextView) Findviewbyid (R.id.result_text); Querybutton=(Button) Findviewbyid (R.ID.QUERY_BTN); Querybutton.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {phonesec=Phonesecedittext.gettext (). toString (). Trim (); //simple to determine whether the user entered the mobile phone number (paragraph) is legal                if("". Equals (phonesec) | | Phonesec.length () < 7) {                    //give the error hintPhonesecedittext.seterror ("You entered the mobile phone number (paragraph) is wrong!" ");                    Phonesecedittext.requestfocus (); //TextView empty to display query resultsResultview.settext (""); return; }                //Android4.0 will not be able to access the network in the main thread later, so the new threadRunnable r =NewNetworkhandler (); Thread Thread=NewThread (R);                Thread.Start (); //because the network connection takes a certain time, in order to display the network information on the main interface, the sleep () method is simply implemented, so that the main thread waits for the network information reading to complete.                 Try{Thread.Sleep (300); } Catch(interruptedexception e) {e.printstacktrace (); }                if(Result! =NULL) {Resultview.settext (result);    }            }        }); }    /*** Mobile phone number Segment Attribution Enquiry * *@paramphonesec Mobile phone number segment*/    Private voidGetremoteinfo (String phonesec) {//name SpaceString nameSpace = "http://WebXml.com.cn/"; //called method nameString methodName = "Getmobilecodeinfo"; //EndPointString endPoint = "Http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx"; //SOAP Action is namespace + method nameString soapaction = "Http://WebXml.com.cn/getMobileCodeInfo"; //specifies the namespace of the WebService and the method name of the callSoapobject RPC =NewSoapobject (NameSpace, methodName); //set the two parameters that need to be passed in to call the WebService interface Mobilecode, UserIdRpc.addproperty ("Mobilecode", phonesec); Rpc.addproperty ("UserId", "" "); //generates SOAP request information that calls the WebService method and specifies the version of SoapSoapserializationenvelope envelope =NewSoapserializationenvelope (SOAPENVELOPE.VER12); Envelope.bodyout=RPC; //sets whether to invoke the dotnet developed WebServiceEnvelope.dotnet =true; //equivalent to envelope.bodyout = RPC;envelope.setoutputsoapobject (RPC); Httptransportse Transport=NewHttptransportse (EndPoint); Try {            //Call WebServiceTransport.call (soapaction, envelope); } Catch(Exception e) {e.printstacktrace (); System.out.println ("Call WebService Exception"); }        //get the returned dataSoapobject Object =(Soapobject) Envelope.bodyin; if(Object! =NULL)            //gets the returned resultresult = Object.getproperty (0). toString (); Else{System.out.println ("Object is empty"); }    }    Private classNetworkhandlerImplementsRunnable {@Override Public voidrun () {getremoteinfo (phonesec); }    }}

Note: Do not forget to add permissions to the manifest file <uses-permission android:name= "Android.permission.INTERNET"/>

Of course, from a rigorous point of view, it is best to add the phone is not connected to the judgment of the net.

This example is tested in a WiFi environment without exception and is not guaranteed to be normal in the case of traffic usage.

Demo Download: http://pan.baidu.com/s/1dDIiUcx

Reference: http://blog.sina.com.cn/s/blog_5041093f0100856n.html

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.