Android Learning Note WebService implementation of Remote Call + internal principle analysis ...

Source: Internet
Author: User
Tags wsdl

PS: Finally can take time to write blog, busy School of the three-week break practical training plus for the test ... Three weeks, not how to learn ... Hey...

Learning content:

1.WebService implementation of remote method invocation

What is WebService ...

WebService, as the name implies, is the Web services, WebService data transmission format is based on XML document specification, the transmission of information is in the form of XML to complete ... Because XML is not limited by platform and language, it is for this reason that WebService can make remote calls, and the language of the calling service can be arbitrary.

What is the SOAP protocol ...

The SOAP protocol is called the Simple Object Access Protocol, which is used to describe the transmission format of the information ... A SOAP message is actually an XML document, SOAP can specify who the message is sent by, and who receives and processing, which is the encapsulation of soap, which is based on the XML data format and the HTTP transport protocol defines a standard set of data transfer objects ... To be blunt is to complete the transfer of XML data information based on the HTTP protocol ...

What is WSDL ...

If soap is used to complete the transfer of data information, then WSDL is to specify how the data information is passed, WSDL is WebService's description language, the purpose is to describe each function on webservice, we know the premise of function call is: Need to know function , as well as the related parameters that need to be passed by the function call, and the return value, only if we know these points can we invoke a function, then the WSDL is used to accomplish this function, which is based on an XML document, a standard document that a machine can parse ... is actually a specification describing the application function ...

What is UDDI ...

UDDI is the third most important element of webservice, its function is to complete webservice registration and search, the search is actually a lot of methods on the network to find the method we need ... Registration is the generation of a new function ...

The above is the three main elements of WebService, may be a little bit, summed up that is, UDDI completion of the invocation of the service lookup, find the call function, after obtaining the WSDL, we can call it, the process of the call, passed the object is a soap wrapped object ...

How to call WebService is the main ....

The webservice call process is actually very simple ... We just need to know the parameters to be passed when calling the function, and the URL of the function to make the call of the remote method easy ...

Calling webservice needs to use the package to a Ksoap2-android-assembly-3.0.0-jar-with-dependencies.jar ... This package I will give at the end of the ...

Attach a piece of code first ... This is a remote way to call a query for a city's weather conditions ...

 PackageCom.example.webservice_web;Importjava.io.IOException;ImportOrg.ksoap2.SoapEnvelope;ImportOrg.ksoap2.serialization.SoapObject;ImportOrg.ksoap2.serialization.SoapSerializationEnvelope;ImportOrg.ksoap2.transport.HttpTransportSE;Importorg.xmlpull.v1.XmlPullParserException;ImportAndroid.os.Bundle;Importandroid.app.Activity;ImportAndroid.view.Menu;ImportAndroid.view.View;ImportAndroid.widget.EditText;ImportAndroid.widget.TextView;ImportAndroid.widget.Toast; Public classMainactivityextendsActivityImplementsView.onclicklistener {String NAMESPACE= "http://WebXml.com.cn/";//name space ....String url= "Http://www.webxml.com.cn/webservices/weatherwebservice.asmx";//URL of the method:String method_name= "Getweatherbycityname";//the method name that needs to be called ...String soap_action= "Http://WebXml.com.cn/getWeatherbyCityName";//typically namespace + method name ...        /*** The above four properties, we can find through the relevant service information of the method, the relevant information is actually the WSDL document. It contains the contents of the above information ... * We can call this remote method by using WSDL to explicitly specify the parameters that need to be passed in the method invocation ... **/String Weathertoday;       Soapobject detail; //The return value of the receive function ...String Weathernow;    String Weatherwillbe; PrivateTextView TV; PrivateEditText et; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); ET=(EditText) Findviewbyid (r.id.et); Findviewbyid (R.ID.BT). Setonclicklistener ( This); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu); return true; } @Override Public voidOnClick (View v) {//TODO auto-generated Method Stub        Switch(V.getid ()) { CaseR.ID.BT:TV=(TextView) Findviewbyid (r.id.tv); Soapobject RPC=NewSoapobject (NAMESPACE, method_name); String CityName=Et.gettext (). toString (); Rpc.addproperty ("Thecityname", CityName);//Add Parameter: Purpose in order to invoke the method provided by the service side ...            /** Instantiate Soapserializationenvelope object ... **/Soapserializationenvelope Envelope=NewSoapserializationenvelope (SOAPENVELOPE.VER11); Envelope.bodyout=RPC; Envelope.dotnet=true; Envelope.setoutputsoapobject (RPC);//set the output parameter to RPCHttptransportse HT=Newhttptransportse (URL); Ht.debug=true; Try {               //Toast.maketext (Getbasecontext (), "AA", Toast.length_long). Show ();Ht.call (soap_action, envelope); Toast.maketext (Getbasecontext (),"BB", Toast.length_long). Show (); Detail=(Soapobject) envelope.getresponse (); String Date=detail.getproperty (6). toString (); Weathertoday= "\ n weather:" +date.split ("") [1]; Weathertoday=weathertoday+ "\ n temperature:" +detail.getproperty (5). toString (); Weathertoday=weathertoday+ "\ n Wind:" +detail.getproperty (7). toString (); Weathernow=detail.getproperty (8). toString (); Weatherwillbe=detail.getproperty (9). toString (); Tv.settext (Et.gettext (). toString ()+weathertoday); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(xmlpullparserexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        }    }}

Very simple piece of code, but there are a lot of places to say ... WebService call first need to know soap_action,url,method,namespace...url we can directly get to ... As for the other three related information, we can get to it by looking at the WSDL document directly ... Now that we know this information, we can define the SOAP object ... Soap will pass the parameters, need to call the method, define the sending source and the receiving source ... This information is encapsulated in a SOAP object, sent to the server as a data stream, after the server obtains the data, completes the call to the method, and then returns the returned data information to the client in the form of a stream ... The client receives the returned information, and the whole is called by the remote method ... Let's talk about the whole realization process ...

First of all we need to instantiate a soapobject ... Instantiating a Soapobject object requires calling the new function to generate ... Here is the process of invoking the source code ... Instantiate a Soapobject object by passing the namespace and method name:

/**      * Creates a new <code>SoapObject</code> instance.     *     @param  namespace The namespace for the Soap object     @param  name      the Name of the Soap object     *      /Public Soapobject (string namespace, string name) {         this. namespace = namespace;         this. Name = name;    }

So after instantiating an object we need to add the property value to this object, call the AddProperty () method ... In fact, the purpose is to pass parameters ... Here is the source of the call process ...

 /*** Adds a property (parameter) to the object.     This is essentially a sub element. *     * @paramName The name of the property *@paramvalue The value of the property*/    //the source code means to configure two properties for this Soapobject object, one is the name attribute, the other is the value attribute ...     Publicsoapobject AddProperty (String name, Object value) {PropertyInfo PropertyInfo=NewPropertyInfo (); Propertyinfo.name=name; Propertyinfo.type= value = =NULL?PropertyInfo.OBJECT_CLASS:value.getClass (); Propertyinfo.value=value; returnAddProperty (PropertyInfo); }

The above source code we can see, here the property is added is by instantiating the PropertyInfo object, and then call the AddProperty () function again: (Note: Two calls to the function name, but the method is not the same ...) Here to explain the role of the Porpertyinfo object ... Porpertyinfo is a class in which the function of this class is actually a preservation of all attribute information ... (Here the attribute information may not be clear to you ...) is actually the object,integer,string) and other basic types to save, save the way through GetClass () ... Gets information about each class used to assign values ... In fact, it is not difficult to understand that when we call AddProperty () to pass parameters, we need to have the name and value of the parameter, then naturally also have the attribute of the parameter, otherwise, when we get the parameters in the Soapobject object, we can not know what is the property of the passed parameter ... So the PropertyInfo Name,value,type is attached to the initial value ... Finally by calling the AddProperty method: Here the AddProperty (PropertyInfo) has been transferred to the Porpertyinfo object ...

/**      * Adds a property (parameter) to the object. This is essentially a sub element.     *     @param  propertyInfo designated     retainer of desiredproperty **     public soapobject addproperty (PropertyInfo PropertyInfo) {        properties.addelement (PropertyInfo);         returnthis;    }

Here call the Properties.addelement () method ... addelement () method ... The arguments passed are (e Object), where e is actually the vector type ... Vector Presumably everyone knows, is a dynamic object array, by adding objects dynamically ... In this way, the vector keeps all the properties of the object in a loop.

 /**   * Adds the specified object at the end of     This vector. * *   @param   object * The OBJEC     T to add to the vector.  */ public  synchronized  void   AddElement (E object) { if  (elementcount == elementdata.length        ) {Growbyone ();        } elementdata[elementcount  + +] = object;    Modcount  ++; }

The Soapobject object that encapsulates all the parameters is saved. Nature needs to be passed to the remote method ... Complete the call .... The invocation of the remote method here requires the instantiation of the Soapserializationenvelope object ... What is called a serialized object ... The meaning of serialization is actually to convert a class or object into a stream form, so as to facilitate the transfer and storage, the serialization of the class or object without human processing, if not serialized, we need to manually define the storage, forwarding of the format, as well as the conversion into the flow of the need for us to write. This will be quite complicated ... And at the same time deserialization, the general operating environment will automatically restore classes and objects. If the man-made restore ... Will still be very complex ... This is done by serializing the above Soapobject object ... You can specify that the Soapobject object is transmitted in a streaming way ... The following method is called here ...

Soapserializationenvelope envelope=New soapserializationenvelope (SOAPENVELOPE.VER11), the following is the source process .... The instantiation object here needs to specify the version information of the WebService ...

 Public Soapserializationenvelope (int  version)    {        Super(version);        Addmapping (Enc, array_mapping_name, propertyinfo.vector_class);        Default_marshal.register (this);    }

The Addmapping method is called here to save the PropertyInfo object array in the form of a key-value pair in Hashtable ... Finally, the registration of the stored object is completed by the Register method. After the encapsulation registration is completed ... You also need to set the related properties ... This completes the setting of the related property ... Indicates that the encapsulated object is the Soapobject object we defined earlier ... Set the access server to. NET Server ... Set the last output object to still be the Soapobject object ...

Envelope.bodyout=object; envelope.dotnet=true; Envelope.setoutputsoapobject (object);

Once all the objects have been encapsulated, you need to use HTTP to connect the URLs ... Complete the connection of the WSDL address via Httptransportse ... Finally, the call method is used to complete the invocation of the method ... This completes the invocation of the remote method, if the function does not return data, then we do not need to get the ... Only need to complete the upload of data information can be. If there is a return data, we also need to define a soapobject to complete the receiving of the return data ... Get the information we need from the returned data and display it in our own application, thus completing the call to the remote method ...

Httptransportse ht=Newhttptransportse (URL); Ht.debug=true; Try{Ht.call (soap_action, envelope);
Detail= (Soapobject) envelope.getresponse (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(xmlpullparserexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }

Just like the beginning of the code, the last return is a Soapobject object, we receive this object can get some of the data we want to information ...

(Note: You need to set permissions by using network services ... <uses-permission android:name= "Android.permission.INTERNET"/>) ....

This completes the call of the remote method, realizes the communication between the application of the different platform ... Enables seamless connection of Web services ...

Android Learning Note WebService implementation of Remote Call + internal principle analysis ...

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.