Basic knowledge about Android 10: WebService 01: ksoap2

Source: Internet
Author: User

This document describes how to use WebService on the android client. The first is about ksoap2 and the second is about rest.

Basic knowledge about Android 10: WebService 01: ksoap2

Basic knowledge about Android 10: WebService 02: Rest

1. Overview of WebService

This part is from

1.1 What is Web Services?

  • Web services is an application component.
  • Web Services uses open protocols for communication
  • Web services are independent (self-contained) and Self-describing
  • Web services can be discovered through the use of UDDI
  • Web services can be used by other applications
  • XML is the basis of Web Services

1.2 How does it work?

  • The basic web services platform is XML + HTTP.
  • HTTP is the most common Internet protocol.
  • XML provides a language that can be used between different platforms and programming languages.
  • Elements of the Web Services Platform:
  • Soap (Simple Object Access Protocol)
  • UDDI (General description, discovery and integration)
  • WSDL (Web Services Description Language)

1.3 web services have two types of applications

  • Reusable application components

Some features are often used by different applications. So why do we need to develop them repeatedly?
Web services can provide application components as services, such as exchange rate conversion, weather forecasting, or even language translation.
Ideally, each application component has only one of the best versions, so that anyone can use it in their applications.

  • Connect existing software

By providing a way for different applications to link their data, Web services helps solve the problem of collaborative work.
By using web services, you can exchange data between different applications and platforms.

1.4 Implementation Means

WebService is generally divided into. NET and Java versions. Today we mainly implement the Java version of WebService, And the. NET version is relatively simple. What is WebServices?
It is a universal model for building applications and can be run in any operating system that supports network communication. It is a new Web Application Branch, it is a self-contained, self-describing, and modular application that can be released, located, and called through the Web. Web Service is an application component that logically provides data and services for other applications. each application accesses the Web Service through the network protocol and some standard data formats (HTTP, XML, and SOAP). The results are obtained through the internal execution of the web service. web services can execute any function from simple requests to complex business processing. After deployment, other Web service applications can discover and call the services deployed by the application.
Key Technologies and rules
The following key technologies and rules are used to build and use web services:
1. xml: Standard Method for describing data.
2. Soap: indicates the Information Exchange Protocol.
3. WSDL: Web Service Description Language.
4. UDDI: Universal Description, discovery, and integration. It is a platform-independent, XML-based protocol used to describe commerce on the Internet.

  • XML

The Extensible Markup Language (XML) is the basic format for data representation on the Web service platform. In addition to ease of establishment and analysis, XML has the primary advantage of being platform-independent and vendor-independent. Independence is more important than technical superiority: software vendors will not choose a technology invented by competitors.

  • Soap

Soap is the standard communication protocol of Web Service, abbreviated as Simple Object Access protocoll, Simple Object Access Protocol. It is a standardized XML Message format for message transmission.

  • WSDL

The full name of WSDL is Web Service Description Language, which is a Web Service Description Language Based on XML format. The main purpose is that the Web service provider transfers all relevant content of its Web Service, such as the transmission mode, service method interface, interface parameters, and service path of the provided service, generate a complete document and publish it to the user. You can use this WSDL document to create a SOAP request message and send it to the WebService provider over HTTP. After the Web service completes the service request, it returns the soap Response Message to the requester, the service requestor then parses the soap returned message into something that he can understand based on the WSDL document.

  • UDDI

Register and publish Web Services. UDDI is a standard for creating registry services, so that you can register and publish your web services for user search. however, when a service provider wants to publish its web service to the world to find its service externally, the service provider can register its web service to the corresponding UDDI commercial registration website, at present, there are four UDDI commercial registration websites around the world, such as IBM. Because the url uri of the web service has been given in the WSDL file, the external interface can call the corresponding web service directly through the URI provided by the WSDL. Therefore, UDDI is not a required Web
Service components, the service provider can not register UDDI.

2. Use of Android WebService

This article only describes how to use WebService from an Android mobile phone.

Currently, common WebServices are ksoap2 and rest. Next we will introduce them separately.
3. Use ksoap2 to call WebService

3.1 obtain and use the kSOAP package
We need some libraries in the PC machine Java client, such as xfire, axis2, and cxf, to support WebService access. However, these libraries are not suitable for Android mobile clients with limited resources, anyone who has worked on Java me knows that there is a third-party class library kSOAP, which can help us get WebService calls from the server. Of course, kSOAP has provided a jar package based on Android, let's get started:
First download kSOAP package: ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar package
Create an android project and place the downloaded kSOAP package in the lib directory of the android project: Right-click and choose build path> Configure build path -- select libraries,

The following are seven steps to call the WebService method:

First, instantiate the soapobject object, specify the namespace of the WebService (you can view the namespace from the relevant WSDL document), and call the method name. For example:

// Namespace Private Static final string servicenamespace = ""; // call the method (available city) Private Static final string getsupportcity = "getsupportcity "; // instantiate the soapobject object soapobject request = new soapobject (servicenamespace, getsupportcity );

Step 2: If the method has parameters, set the call method parameters. This step is optional. If the method does not have parameters, skip this step.
Request. addproperty ("parameter name", "parameter value ");

Note that although the 1st parameters of the addproperty method represent the parameter name of the method to be called, the parameter value is not necessarily the same as the method parameter name in the WebService class of the server, you only need to set parameters in the same order.
Step 3: Set the SOAP request information (the parameter part is the SOAP Protocol version number, which is consistent with the version number in the WebService you want to call ):

// Obtain the serialized envelope soapserializationenvelope envelope = new soapserializationenvelope (soapenvelope. ver11); envelope. bodyout = request;

When creating a soapserializationenvelope object, you must use the soapserializationenvelope class constructor to set the SOAP Protocol version number. This version number must be set according to the WebService version number on the server. After creating a soapserializationenvelope object, do not forget to set the bodyout attribute of the soapserializationenvelope class. The value of this attribute is the soapobject object created in step 1.

Step 4: Register envelope,
(New kerberalbase64 (). Register (envelope );
Step 5: Build the transmission object and specify the URL of the WSDL document:

// Request URL Private Static final string serviceurl = ""; // Android transmission object androidhttptransport transport = new androidhttptransport (serviceurl); transport. DEBUG = true;

Step 6: Call WebService (where the parameter is 1: namespace + method name, 2: envelope object ):, envelope);

The 1st parameters of the call method are generally null. The 2nd parameters are the soapserializationenvelope object created in step 1.

Step 7: parse the returned data:

If (envelope. getresponse ()! = NULL) {return parse (envelope. bodyin. tostring ());} /*************** Parse XML * @ Param Str * @ return */Private Static list <string> parse (string Str) {string temp; List <string> List = new arraylist <string> (); If (STR! = NULL & Str. length ()> 0) {int start = Str. indexof ("string"); int end = Str. lastindexof (";"); temp = Str. substring (START, end-3); string [] test = temp. split (";"); For (INT I = 0; I <test. length; I ++) {if (I = 0) {temp = test [I]. substring (7);} else {temp = test [I]. substring (8);} int Index = temp. indexof (","); list. add (temp. substring (0, index) ;}} return list ;}

This will be successful.

3.2 Example: Query product information through WebService
This example involves a WebService server program and an ophone client program. You can directly copy the server program (axis2 directory) to the <tomcat installation directory> \ webapps directory, start Tomcat, and enter the following URL in the browser address bar:

Http: // localhost: 8080/axis2

If the page shown in 2 is displayed in the browser, the server program is successfully installed.

The WebService program on this server is searchproductservice. In fact, searchproductservice is a Java class, which is mapped to WebService by using axis2. There is a getproduct method in this class. This method has a string type parameter, indicating the product name. This method returns a product object with three attributes: name, price, and productnumber. You can use the following URL to view the WSDL document of searchproductservice.

Http: // localhost: 8080/axis2/services/searchproductservice? WSDL

Page 3 shows the WSDL document.

The black box in Figure 3 contains the WebService namespace, which is also the 1st parameter value of the soapobject constructor. This WebService program can be tested directly using the following URL.

Http: // localhost: 8080/axis2/services/searchproductservice/getproduct? Param0 = iPhone

Test Result 4 is displayed.

As shown in the test results, axis2 directly converts the product object returned by the getproduct method into an XML document (actually in the soap format) and returns the result.
The following describes how to use ksoap2 to compile the ophone client that calls WebService. The Code is as follows:

Package net. blogjava. mobile. wsclient; import Org. ksoap2.soapenvelope; import Org. ksoap2.serialization. soapobject; import Org. ksoap2.serialization. soapserializationenvelope; import Org. ksoap2.transport. httptransportse; import android. app. activity; import android. OS. bundle; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. edittext; import Ndroid. widget. textview; public class main extends activity implements onclicklistener {@ override public void onclick (view) {edittext etproductname = (edittext) findviewbyid (R. id. etproductname); textview tvresult = (textview) findviewbyid (R. id. tvresult); // the URL of the WSDL document. is the pc id string serviceurl = "http: // 8080/axis2/services/searchproductservice? WSDL "; // define the called WebService method name string methodname =" getproduct "; // Step 4: Create a soapobject object, specify the WebService namespace and the called method name soapobject request = new soapobject ("http: // service", methodname); // Step 4: Set the request parameter of the WebService method. addproperty ("productname", etproductname. gettext (). tostring (); // Step 2: Create the soapserializationenvelope object and specify the version of the WebService soapserializationenvelope envelope = new soapserializationenvelope (soape Nvelope. ver11); // set the bodyout attribute envelope. bodyout = request; // Step 2: Create an httptransportse object and specify the URL of the WSDL document httptransportse ht = new httptransportse (serviceurl); try {// Step 3: Call WebService ht. call (null, envelope); If (envelope. getresponse ()! = NULL) {// step 6th: Use the getresponse method to obtain the returned result soapobject = (soapobject) envelope. getresponse (); // get the property value of the product object using the getproperty method string result = "Product Name:" + soapobject. getproperty ("name") + "\ n"; Result + = "product quantity:" + soapobject. getproperty ("productnumber") + "\ n"; Result + = "product price:" + soapobject. getproperty ("price"); tvresult. settext (result);} else {tvresult. settext ("None of this product. ") ;}} catch (exception e) {}}@ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); button btnsearch = (button) findviewbyid (R. id. btnsearch); btnsearch. setonclicklistener (this );}}

Note the following when writing the above Code:
1) in step 1, the 2nd parameter values of the addproperty method are productname. Although this value is the parameter name of the getproduct method, the 1st parameter values of the addproperty method are not limited to productname, you can set this parameter to any other string (but this value must be valid in XML, for example, it is not a string reserved for XML, such as "<", "> ).
2) the property value of the product object can be obtained through the getproperty method of the soapobject class. These property names are the property names in the test results shown in Figure 4.
Run this example, enter "HTC Hero" in the text box, and click "query". The query result shown in 5 is displayed below the button.

Prevent UI component Blocking
In terms of functions, the Code provided in this example does not have any problems. However, some readers may worry that, if many WebService users call the service, the server may be slow to respond, or the IP address of the service may be incorrect, in these cases, the buttons and text box components on the user interface cannot respond to other actions of the user as they are "dead. Of course, there is a possibility of such a situation, especially in a complex network environment, this will make the entire software system very bad in terms of user experience.
Both users and developers want to improve this bad situation. The most ideal status is that when you click the button to call the WebService method, even if the WebService method does not return immediately for some reason, the components on the interface will still be active, that is, you can still use other components in the current interface.
In ophone, asynchronous methods can be used to achieve this goal. Asynchronization is actually implemented through multiple threads. Generally, new thread (this). Start () is used to create and start a thread. However, this section does not use thread to implement Asynchronization. Instead, it uses the asynctask class to execute the task (WebService call) in the background.
Next, let's take a look at the improved code.

Package net. blogjava. mobile. wsclient; import Org. ksoap2.soapenvelope; import Org. ksoap2.serialization. soapobject; import Org. ksoap2.serialization. soapserializationenvelope; import Org. ksoap2.transport. httptransportse; import android. app. activity; import android. OS. asynctask; import android. OS. bundle; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android Oid. widget. edittext; import android. widget. textview; public class main extends activity implements onclicklistener {private edittext etproductname; private textview tvresult; Class wsasynctask extends asynctask {string result = ""; @ override protected object doinbackground (object... params) {try {string serviceurl = "http: // 8080/axis2/services/searchproductservice? WSDL "; string methodname =" getproduct "; soapobject request = new soapobject (" http: // service ", methodname); Request. addproperty ("productname", etproductname. gettext (). tostring (); soapserializationenvelope envelope = new soapserializationenvelope (soapenvelope. ver11); envelope. bodyout = request; httptransportse ht = new httptransportse (serviceurl); ht. call (null, envelope); If (envelope. getresponse ()! = NULL) {soapobject = (soapobject) envelope. getresponse (); Result = "Product Name:" + soapobject. getproperty ("name") + "\ n"; Result + = "product quantity:" + soapobject. getproperty ("productnumber") + "\ n"; Result + = "product price:" + soapobject. getproperty ("price");} else {result = "This product does not exist. ";}} catch (exception e) {result =" WebService call error. ";}// you must use the POST method to update the UI component tvresult. post (New runnable () {@ override public void run () {tvresult. settext (result) ;}}); return NULL ;}@ override public void onclick (view) {// asynchronously executes the task of calling WebService new wsasynctask(cmd.exe cute ();} @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); button btnsearch = (button) findviewbyid (R. id. btnsearch); btnsearch. setonclicklistener (this); etproductname = (edittext) findviewbyid (R. id. etproductname); tvresult = (textview) findviewbyid (R. id. tvresult );}}

The core code for WebService calling is exactly the same as the code in the example. Note the following points when writing the above Code.
1. Generally, a subclass of asynctask needs to be compiled to execute tasks in the background.
2. The core method of asynctask is doinbackground. When the execute method of the asynctask class is called, The doinbackground method is executed asynchronously. Therefore, you can write the code for executing the task in the doinbackground method.
3. Because the textview component in this example is created in the main thread (ui thread), The textvew component cannot be directly updated in other threads (the thread where the doinbackground method is located. To update the textview component, you must use the post method of the textview class. The parameter of this method is a runnable object. You need to write the code of the updated textview component in the run method of the runnable interface.
4. Although the UI component cannot be updated in other threads, the value of the UI component can be directly read from other threads. For example, the value of the edittext component is directly read in the doinbackground method.
5. Call the execute method of the asynctask class and return immediately. The parameter of the execute method is the parameter of the doinbackground method. The return value of doinbackground.pdf can be obtained through asynctask.exe cute (...). Get.

You can change the IP address in this example to another value to see if other content can be entered in the text box after you click the button. If this IP address is correct and WebService is accessible, the corresponding return value will be output in the textview component.



Use ksoap2 in ophone to call WebService

WebService for Android Development (Java Edition)

Android and server-side data interaction (Integrate Android + WebService Based on SOAP protocol)

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: 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.